How can I make setInterval also work when a tab is inactive in Chrome?

后端 未结 13 1966
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 09:59

I have a setInterval running a piece of code 30 times a second. This works great, however when I select another tab (so that the tab with my code becomes inacti

13条回答
  •  醉酒成梦
    2020-11-21 10:51

    It is quite old question but I encountered the same issue.
    If you run your web on chrome, you could read through this post Background Tabs in Chrome 57 .

    Basically the interval timer could run if it haven't run out of the timer budget.
    The consumption of budget is based on CPU time usage of the task inside timer.
    Based on my scenario, I draw video to canvas and transport to WebRTC.
    The webrtc video connection would keep updating even the tab is inactive.

    However you have to use setInterval instead of requestAnimationFrame.
    it is not recommended for UI rendering though.

    It would be better to listen visibilityChange event and change render mechenism accordingly.

    Besides, you could try @kaan-soral and it should works based on the documentation.

提交回复
热议问题