jQuery Timer在循环中使用时失败

时间:2019-06-18 17:09:30

标签: jquery for-loop timer

我的页面上有任意多个div,每个div需要一个单独的计时器。我已经设置了此jsfiddle。循环中处理计时器的所有部分均设置为计时器0,并且在运行脚本时更新了第一个div。但是在此jsfiddle中,我将对项目0的所有引用都更改为使用idx var,并且在运行时没有div的更新。使用idx的代码如下所示。有人可以指出我要去哪里了吗?

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

0 个答案:

没有答案