切换选项卡时,角度4 setinterval暂停

时间:2017-08-24 17:17:07

标签: javascript angular

我的setInterval计时器在退出选项卡时暂停,当切换回选项卡时恢复我希望解决方案使其在切换选项卡时继续计数

这里是GIF图片显示发生了什么

enter image description here

这是我的代码:

  startCountDown(time) {
    clearInterval(this.countDownInterval);
    this.timeLeft = time * 100;
    if (time === 0) {
      return;
    }

    this.countDownInterval = setInterval(() => {
      this.timeLeft -= 1;
      if (this.timeLeft === 0) {
        clearInterval(this.countDownInterval);
      }
    }, 10);
  }
  updateTimer() {
    if (this.timeLeft > 0) {
      $('.rolling').fadeIn(200);
      $('.rolling-inner').html('<div>' + (this.timeLeft / 100).toFixed(2).replace('.', ':') + '</div>');
    } else {
      $('.rolling').fadeOut(200);
    }
  }
  set timeLeft(x) {
    this._timeLeft = x;
    this.updateTimer();
  }
  get timeLeft() {
    return this._timeLeft;
  }

1 个答案:

答案 0 :(得分:2)

Setinterval没有行为不端,这就是它的属性。但您可以跟踪选项卡选择操作,并使用现有时间添加待处理的空闲持续时间。

这是跟踪标签选择和模糊的代码

$(window).on("blur focus", function(e) { 
    var prevType = $(this).data("prevType"); 

    if (prevType != e.type) { 
        switch (e.type) { 
            case "blur": break; 
            case "focus":  break; 
        } 
    } 

    $(this).data("prevType", e.type); 
})
相关问题