SetInterval的替代方法是什么?

时间:2019-09-13 20:14:28

标签: javascript jquery

我写了一个24小时倒数计时器,但是它很慢,有时系统时钟和计时器之间的时差达到2小时。我想知道是否存在setinterval的替代方法,并将其放置在我的代码中。

var _tick = setInterval(function() {
    if ((remSeconds) > 0) {
      if (hoursCounter > 0) {
        if (minutesCounter == 0 && secondsCounter == 0) {
          minutesCounter = 60;
          hoursCounter = hoursCounter - 1;
        }
      }
      if (secondsCounter == 0) {
        secondsCounter = 60;
        minutesCounter = minutesCounter - 1;
      }
      secondsCounter = secondsCounter - 1;
      remSeconds = remSeconds - 1;

      $seconds.text(formatNumber(secondsCounter));
      $minutes.text(formatNumber(minutesCounter));
      $hours.text(formatNumber(hoursCounter));
    } else {
      clearInterval(_tick);
      document.getElementById("tRemaining").innerHTML = "EXPIRED";
    }
  },
  1000);

1 个答案:

答案 0 :(得分:1)

您可以这样做:

var startTime = Date.now();
var duration = 1000*60*60*24;  // set duration to 24h

var _tick = setInterval(function() {
   let remSeconds = Math.floor((duration - (Date.now()-startTime))/1000);
   if ((remSeconds) > 0) {
      let remHours = Math.floor(remSeconds/3600);
      remSeconds -= remHours*3600;
      let remMins = Math.floor(remSeconds/60);
      remSeconds -= remMins*60;
      document.getElementById("tRemaining").innerHTML = remHours+':'+remMins+':'+remSeconds;
   } 
   else {
      clearInterval(_tick);
      document.getElementById("tRemaining").innerHTML = "EXPIRED";
   }
},
1000);
<div id="tRemaining"></div>

如果您想要干净的输出,还需要添加一些内容来处理0填充,以避免出现类似23:7:31的情况,但是必不可少的。