I want to show countdown in each of my divs. Right now I get the seconds from my database and store in in data-countdown attribute and then use the following js code for countdown. Only the first div changes the value every second and the other ones do not change. Here is the fiddle: http://fiddle.jshell.net/j61qs7oc/
//imagine this line of code in every loop of a for loop so $remaining will be different
<div style="font-size: 25px; color:#e3b40b ; font-weight: 600;" data-countdown="'.$remaining.'"><i class="fa fa-spinner fa-pulse"></i></div>
here is the js code
$('[data-countdown]').each(function() {
finalDate = $(this).data('countdown');
var $this = $(this);
timeout = null;
time = null;
startCountdown($this,finalDate, 1000, end);
function startCountdown(display,timen, pause, callback) {
time = timen;
display.html(timen);
if (timen == 0)
callback();
else {
clearTimeout(timeout);
timeout = setTimeout(function () {
startCountdown(display,timen - 1, pause, callback)
}, pause);
}
}
function end() {
alert();
}
});
When you declare a variable without using the var
keyword, you're creating a global. So each instance of your countdown is overwriting the previous value of finalDate
, timeout
, and time
. Try adding var
before each of those lines and it should do what you need. i.e.:
var finalDate = $(this).data('countdown');
var $this = $(this);
var timeout = null;
var time = null;
startCountdown($this,finalDate, 1000, end);