This tutorial demonstrates a jQuery countdown timer that decrements from 10 every second. This is achieved by recursively calling setTimeout
within the timer function. Below is the code.
jQuery Code
jQuery(document).ready(function() { let countdown; let countdownNumber; function countdownInit() { countdownNumber = 11; countdownTrigger(); } function countdownTrigger() { if (countdownNumber > 0) { countdownNumber--; $('#countdown_text').html(countdownNumber); //Corrected selector and method if (countdownNumber > 0) { countdown = setTimeout(countdownTrigger, 1000); //Simplified setTimeout call } } } function countdownClear() { clearTimeout(countdown); } countdownInit(); //Start the timer on page load });
HTML Code
<div id="countdown_text">Placeholding text</div>
Frequently Asked Questions about jQuery Timers
This section addresses common questions regarding jQuery timers.
Q: How do I build a countdown timer with jQuery?
A: Use setInterval
for repeated execution at a set interval. Here's a concise example:
let count = 10; let counter = setInterval(function() { count--; if (count < 0) { clearInterval(counter); return; } $("#timer").text(count + " secs"); }, 1000);
Q: How can I pause a jQuery timer?
A: Use clearInterval
to stop a timer started with setInterval
.
function pauseTimer() { clearInterval(counter); }
Q: How to resume a paused jQuery timer?
A: JavaScript doesn't directly resume timers. Restart it with setInterval
using the current count value.
function resumeTimer() { counter = setInterval(function() { count--; if (count < 0) { clearInterval(counter); return; } $("#timer").text(count + " secs"); }, 1000); }
Q: How to create a delayed function execution in jQuery?
A: jQuery's .delay()
method adds a delay before executing a function within an animation chain.
$("#myDiv").delay(2000).fadeIn(400);
Q: How to create a repeating timer in jQuery?
A: setInterval
is the key for repeatedly executing a function.
setInterval(function() { alert("Hello"); }, 3000);
The above is the detailed content of Using SetTimeout to Make a jQuery Timer. For more information, please follow other related articles on the PHP Chinese website!