Skip to content Skip to sidebar Skip to footer

SetInterval Slows Down With Tab/window Inactive

I build a web app and I use setInterval with 500ms timer for some clock. When the window is active the clock runs perfect, I use that: var tempTimer = 0; setInterval(function () {

Solution 1:

Yes, this behavior is intentional.

See the MDN article:

In (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2) and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see bug 633421 for more information about this in Mozilla or crbug.com/66078 for details about this in Chrome.

And the spec says:

Note: This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.


Solution 2:

You seem to want a timer that increments every half second. You can do that much more accurately by keeping track of the total time since you started and doing some math.

var tempTimer = 0;
var startedTimer = Date.now();
setInterval(goTimer, 250); // a little more often in case of drift

function goTimer() {
    tempTimer = Math.floor((Date.now() - startedTimer) / 500);
    $("#timer").val(tempTimer);
}

See this work here: http://jsfiddle.net/4Jw37/2/

So this does update every half second, but it doesn't need to. If it skips a few beats it will fix itself the next time it fires because it's recalculating each time based on the time since it started tracking. The number of times the function runs is now has no effect on the value of the counter.

So put in another way, do not ask how many times you incremented the count. Instead ask how many half second segments have passed since you started.


Solution 3:

For time interval, Browsers may not behave similar for both active and inactive window.

What you can do, When you are setting the time interval you can save the timestamp(initial time). On window.onfocus, take on there timestamp (now) find the difference between initial time and now and use that update the tempTimer.


Post a Comment for "SetInterval Slows Down With Tab/window Inactive"