I have a table and on each row I want to run timer according to different max count number for each row.
<tr>
<td class='timer' data-maxTime='10'></td>
</tr>
<tr>
<td class='timer' data-maxTime='20'></td>
</tr>
<script>
$(".timer").each(function(){
var count = $(this).attr("data-maxTime");
runTimer($(this),count);
});
function runTimer(ele,count){
interval = setInterval(function() {
timer = count.split(':');
minutes = parseInt(timer[0], 10);
seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
clearInterval(interval);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
if(minutes > -1){
ele.html(minutes + ':' + seconds);
rideTime = minutes + ':' + seconds;
}
},1000);
}
</script>
Timer is running for each case , but there is a delay of 1 second for each row. Can anyone please suggest, how these timers start exactly at same time ?
The problem most probably lies in your runTimer function, because you are assigning the result of setInterval to an undefined variable (interval), which will become a global variable. When you call runTimer for the second time, you are actually overwriting that global variable.
Try defining your interval variable first.