jquery SetInterval的替代方案是什么?

ruarlubt  于 2023-05-17  发布在  jQuery
关注(0)|答案(2)|浏览(190)

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

olqngx591#

你可以这样做:

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这样的东西,但本质是存在的。

68bkxrlz

68bkxrlz2#

const mainFunc = () => {
    console.log('Call')
    setTimeout(() => {
        mainFunc()

    },4000)

};
mainFunc();

相关问题