JSFiddle - React, Tailwind, and code Playground

by Bob Wilson

HTML

<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>

JavaScript

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);
  }
}