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

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

    Just do this:

    var $div = $('div');
    var a = 0;
    
    setInterval(function() {
        a++;
        $div.stop(true,true).css("left", a);
    }, 1000 / 30);
    

    Inactive browser tabs buffer some of the setInterval or setTimeout functions.

    stop(true,true) will stop all buffered events and execute immediatly only the last animation.

    The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).

提交回复
热议问题