Reputation: 121
var sec = 10
var timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
} }, 1000);
html
<div id="timer"><span>10</span> seconds</div>
<a href="#" id="recount">Recount</a>
What I want to do when I click recount is to recount back to 10 seconds the timer?
How can I possibly done it?
It is better to use setInterval()
or setTimeout()
?
Upvotes: 1
Views: 658
Reputation: 707546
Factor out your code into functions so you can call the same code on startup or when the link is clicked. You can see it working here: http://jsfiddle.net/jfriend00/x3S7j/. This even allows you to click the link during the countdown and it will start over.
$("#recount").click(function() {
initCounter(10);
});
var remainingTime;
var runningInterval = null;
function initCounter(duration) {
function stopCounter() {
if (runningInterval) {
clearInterval(runningInterval);
runningInterval = null;
}
}
stopCounter(); // stop previously running timer
remainingTime = duration; // init duration
$('#timer span').text(remainingTime); // set initial time remaining
runningInterval = setInterval(function() { // start new interval
$('#timer span').text(remainingTime--);
if (remainingTime < 0) {
stopCounter();
}
}, 1000);
}
initCounter(10);
Upvotes: 2
Reputation: 160922
You can just add a click handler and factor out your code in a separate method:
var sec = 10;
var timer;
function startCountdown() {
if (timer) clearInterval(timer);
sec = 10;
timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
}
}, 1000);
}
$(function() {
startCountdown();
$("#recount").click(startCountdown);
});
Upvotes: 2
Reputation: 81404
When you click recount, you should
sec = 10;
clearInterval(timer);
timer = setInterval(that_function, 1000);
Also, there's a difference between setInterval
and setTimeout
. setInterval
schedules the function to be called every some milliseconds. setTimeout
schedules the function to be called once, after some milliseconds.
Upvotes: 1