【问题标题】:Tab-switching while having a countdown running [duplicate]在倒计时运行时切换标签[重复]
【发布时间】:2018-09-01 12:47:21
【问题描述】:

每当我有一个快速的间隔来运行计时器时,只要在间隔暂停时切换选项卡,它就会出现故障。每当我使用较大的间隔时,它工作得很好,但每当我使用较小的间隔时,它会在标签切换期间暂停。

我想要一个更快的计时器,不知何故不会暂停,有什么想法吗?

代码

var GLOBAL_TIMER_INTERVAL = 60 * 1000,
        GLOBAL_TIMER_TIMEOUT = 60 * 1000;

function countdownInterval(){
    var interval = setInterval(function(){
    if(GLOBAL_TIMER_INTERVAL <= 0){
        clearInterval(interval);
      return;
    }

    GLOBAL_TIMER_INTERVAL = GLOBAL_TIMER_INTERVAL - 10;
    $('.countdown-interval').text(GLOBAL_TIMER_INTERVAL);
  }, 10);
}

countdownInterval();

function countdownTimeout(){
    setTimeout(function(){
    if(GLOBAL_TIMER_TIMEOUT <= 0){
        return;
    }

    GLOBAL_TIMER_TIMEOUT = GLOBAL_TIMER_TIMEOUT - 10;
    $('.countdown-timeout').text(GLOBAL_TIMER_TIMEOUT);
    countdownTimeout();
    }, 10);
}

countdownTimeout();

JSFiddle

【问题讨论】:

  • 使用Date获取实时差异
  • @JonasW。所以我定义了开始日期,然后在间隔中每次更新日期,所以当用户回来时它仍然会计算准确的时差?
  • @orpheuZ 完全是 :)
  • @JonasW。我试试看,谢谢!

标签: javascript


【解决方案1】:

非阻塞计时器:

  class Timer {
   constructor(task){
     this.task = task;
   }

   interval(ms){
     const end = +new Date() + ms;
     const check = () => {
       if(end > +new Date){
          this.task();
          interval(ms);
       } else {
          setTimeout(check, 100);
      }
      check();
    }
  }

所以你可以这样做:

  const log = new Timer(() => console.log("done"));
  log.interval(1000);

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多