I have a page with any number of div's and I need a separate timer for each div. I have setup this jsfiddle. The parts in the loop that deal with which timer are all set to timer 0 and when the script is ran, the first div is updated. But in this jsfiddle I have changed all of the references to item 0 to use the idx var and when ran none of the div's are updated. The code using idx is shown below. Would someone please point out where I'm going wrong?
<div><span id="time-left-0">1.59</span></div>
<div><span id="time-left-1">2.59</span></div>
<div><span id="time-left-2">3.59</span></div>
<script>
var timer_ctr = 3;
var timerID = Array(timer_ctr).fill(0);
var timeLeft = Array(timer_ctr).fill(0);
var idx;
for (idx = 0; idx < timer_ctr; idx++) {
if ($("#time-left-" + idx).length === 0) {
clearInterval(timerID[idx]);
} else {
timerID[idx] = setInterval(function() {
var ct = 0;
var newtime = 0;
if (timeLeft[idx]) { //timer has ran so just update the display
ct = timeLeft[idx];
newtime = ct - 0.01;
if (newtime == 0.99) {
newtime -= .40; //gives 59 seconds
}
} else {
ct = $("#time-left-" + idx).text(); //get the string
ct = ct.replace(":", "."); //make it appear as a float
ct = parseFloat(ct); //convert to float
newtime = (ct == Math.floor(ct)) ? ct - 1 + .59 : ct - .01; //change to next second down
}
newtime = newtime.toFixed(2); //round it
timeLeft[idx] = newtime; //save for next pass
newtime = newtime.toString(); //convert to string for display
var newtime_str = newtime.replace('.', ':'); //change to show separator for time
if (newtime > 0) {
$("#time-left-" + idx).text(newtime_str);
} else {
$("#time-left-" + idx).text('expired');
clearInterval(timerID[idx]);
}
}, 1000);
}
}
</script>