SetInterval的替代方法

SetInterval的替代方法

我已经写了一个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);

最佳答案

您可以这样做:



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之类的东西,但基本内容就在那里。

07-24 15:29