简体   繁体   English

当失去对选项卡/窗口的关注时,SetInterval 未在 Firefox 中运行

[英]SetInterval not running in Firefox when lost focus on tab/window

I have a setInterval function that do countdown of time.我有一个可以倒计时的setInterval函数。

  startCountDownWorker() {
    this.worker= setInterval(() => {
      this.countDown--;

      // When count timer reach zero
      if (this.countDown === 0) {

        // Clear decrement for count down
        clearInterval(this.worker);
        }
      }
    }, 1000);
  }

The function was tested on Chrome , Firefox , Opera , Safari , its working fine on all except Firefox .该功能在ChromeFirefoxOperaSafari上进行了测试,在除Firefox之外的所有设备上都可以正常工作。 When lost focus on Tab/Window on Firefox , the function stopped and only resume when I focus back on the Tab.当在Firefox上失去对 Tab/Window 的关注时,该功能停止并仅在我重新关注 Tab 时恢复。 Any ways to solve this issue ??有什么办法可以解决这个问题??

Browsers do apply a threshold to almost all timing functions when the page is blurred, so all these timed-out functions may only execute once in a while.当页面模糊时,浏览器确实对几乎所有计时功能应用了阈值,因此所有这些超时功能可能只会偶尔执行一次。

Not only this, but there is even an incoming Page Lifecycle API that is being drafted and which would add a discarded and a frozen state to the page's visibility, during which your script would not execute at all, until unfrozen.不仅如此,甚至还有一个正在起草的传入页面生命周期 API ,它将为页面的可见性添加丢弃冻结状态,在此期间您的脚本根本不会执行,直到解冻。

So the best in your position, to be future proof and since you apparently only need a quite long interval, might be to handle the visibility changes and to record the time at which the page got blurred, then when it's focused back, to update your counter based on the actual elapsed time.所以在你的位置上最好的,为了未来的证明,因为你显然只需要一个很长的时间间隔,可能是处理可见性变化并记录页面变得模糊的时间,然后当它重新聚焦时,更新你的计数器基于实际经过的时间。

An other even more reliable solution would be to not actually hold an actual countDown value in your counter, but rather to always compute the delta between the starting time of that counter and now.另一个更可靠的解决方案是不在计数器中实际保存实际的countDown值,而是始终计算该计数器的开始时间和现在之间的增量。 This way, you don't rely on the precision of the browser's timers and you can adjust your timeouts between each tick.这样,您就不必依赖浏览器计时器的精度,并且可以调整每个滴答之间的超时时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM