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

后端 未结 13 1954
被撕碎了的回忆
被撕碎了的回忆 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:54

    Both setInterval and requestAnimationFrame don't work when tab is inactive or work but not at the right periods. A solution is to use another source for time events. For example web sockets or web workers are two event sources that work fine while tab is inactive. So no need to move all of your code to a web worker, just use worker as a time event source:

    // worker.js
    setInterval(function() {
        postMessage('');
    }, 1000 / 50);
    

    .

    var worker = new Worker('worker.js');
    var t1 = 0;
    worker.onmessage = function() {
        var t2 = new Date().getTime();
        console.log('fps =', 1000 / (t2 - t1) | 0);
        t1 = t2;
    }
    

    jsfiddle link of this sample.

提交回复
热议问题