i’m having a little problem with jquery/javascript countdown and i’m hoping you can help me.
so, i have timer function, which has a one parameter, called selector (jquery selector) ..
function timer(selector) {
self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
var interval = setInterval(function() {
sec--;
if (sec >= 0) {
self.find('span.timeout').text(sec);
} else {
setInterval(interval);
}
}, 1000);
}
in, html i have something like this.
<div class="element" id="el1"><span class="timeout">10</span></div>
<div class="element" id="el2"><span class="timeout">10</span></div>
multiple elements with same class and different id’s
and the usage of the function is like this:
$("body").on('click', '.element', function() {
timer(this);
});
on the first click it works just fine, timer counts down.
but when i click on the second div with same class, first counter stops and the second goes from the previous second.
so, how can i do multiple countdowns on same page with js/jquery, so i could click on both elements and both timers work fine?
selfwithvar. As a result,selfbecame a global variable. You were overwriting this global (“shared”) variable when the second timer was being created. So, both timers were from then on, at the same time, ouputting to the second element, causing glitches.clearInterval(interval).http://jsfiddle.net/zKTkj/1/