I have several <span class="timer">342</span>
with different values (seconds).
I want to countdown all of them and thought I could do something like:
$('.timer').ready(function() {
timer = setInterval(function() {
sec = $('.timer').text();
$('.timer').text(--sec);
if (sec == 0) {
clearInterval(timer);
location.href = 'accounts.php';
}
}, 1000);
});
The error is, Javascript gets confused because of more than 1 object of .timer
or something and generates weird values for the spans.
When the first timer hits zero it should reload. Using jQuery. The number of spans is not fixed. I'd really like to keep it simple and don't use an extra plugin or big script file.
.ready
is only used for the document
and marks the point when the DOM is fully parsed. Within this function, this
refers to the document. I'd write it another way:
$(document).ready(function() {
timer = setInterval(function() {
$('.timer').each(function(){
var $this = $(this);
var countdown = parseInt($this.text()) - 1;
$this.text(countdown);
if (countdown == 0) {
clearInterval(timer);
location.href = 'accounts.php';
}
});
}, 1000);
});
Important:
.each
to iterate through every timerparseInt
to get an integer from a stringHere's an Example-Fiddle that works.