I am trying to build multiple timers for my web page, so far I have,
$('.timer').each(function() {
var timer = setInterval(function() {
var time = $(this).text().split(':');
var minutes = parseInt(time[0], 10);
var seconds = parseInt(time[1], 10);
// TIMER RUN OUT
if (!minutes && !seconds) {
// CLEAR TIMER
clearInterval(timer);
// MINUS SECONDS
} else {
seconds -= 1;
}
// MINUS MINUTES
if (seconds < 0 && minutes != 0) {
minutes -= 1;
seconds = 59;
// ADD ZERO IF SECONDS LESS THAN 10
} else {
if (seconds < 10) {
seconds = '0' + seconds;
}
}
// ADD ZERO IF MINUTES LESS THAN 10
if (minutes < 10) {
minutes = '0' + minutes;
}
}, 1000);
});
This doesn't work though! Where am I going wrong!
Thanks
First, inside your setInterval
callback, this
no longer refers to the .timer
element. Try changing that to self
and add var self = this;
before the call to setInterval
. Second, you never write your time back to your .timer
element.
clearInterval
if one clock runs out before the other - cgwebprojects 2012-04-05 23:29
timer
is fine, just like self
is. The context of this
is the only thing that changes in the callback. The timer
variable itself is contained in a closure in your .each
callback, so each .timer
element gets its own variable - Ryan P 2012-04-06 00:55
Are you trying to display a clock counting down? In that case, you're not updating the text after all the calculations. Try adding:
$(this).text(minutes+':'+seconds);