开发者

Function repeating when page not being viewed

开发者 https://www.devze.com 2023-03-31 17:34 出处:网络
I have created a self-repeating function using JavaScript, however when 开发者_Python百科I navigate to another tab open in my browser and go back to the tab containing the function; the function is re

I have created a self-repeating function using JavaScript, however when 开发者_Python百科I navigate to another tab open in my browser and go back to the tab containing the function; the function is repeating at a much faster pace than specified; can anybody shed any light on why this may happen?

Example of JavaScript Used:

function aFunction() {
    var aFunctionVar;
    clearTimeout(aFunctionVar);
    aFunctionVar = setTimeout(aFunction,8000);
    if (condition) {
        //More code to run...
        return false; 
    }
    if (condition) {
        //More code to run...
        return false; 
    } 
};
aFunction();


If your code is using setInterval() and you are running in a browser like Firefox or Chrome, then this is because those browsers are slowing down timers in background tabs while they are in the background (and thus not displayed). When you then bring it back to the foreground, it tries to catch them up. There are a number of possible work-arounds. The best idea is to stop your timer when your browser window is no longer displayed and restart it when the window is displayed again.

On the Chromium blog, Google said:

In the forthcoming Chrome 11 release, we plan to reduce CPU consumption even for pages that are using setTimeout and setInterval. For background tabs, we intend to run each independent timer no more than once per second. This change has already been implemented in the Chrome dev channel and canary builds.

Possible ways to work-around this:

  • Stop your timer/animation when the window is not visible. Restart the timerwhen the window becomes visible.
  • Instead of setInterval, use setTimeout and then just reset the setTimeout each time it fires to create your own repeating interval.
  • Slow your timers down so they don't run afoul of this.

The best option is probably to figure out when to just stop and then restart the timers.

Similar question here: Chrome: timeouts/interval suspended in background tabs?.

FYI, Chrome has new experimental API for detecting page visibility for just this reason. You can read about it here: http://code.google.com/chrome/whitepapers/pagevisibility.html. it helps solve the issue when your page is visible, but doesn't have focus.


Don't use setInterval. Use a setTimeout at the end of the function to have it call itself. Generally your code won't keep running in the background when another tab is active, but with setInterval some browsers try to "catch up" on missed calls once your tab is made active again - which results in the faster operation you describe. Another option is to implement your own pause by reacting when your page loses and regains focus.

0

精彩评论

暂无评论...
验证码 换一张
取 消