Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval slows down with tab/window inactive

Tags:

javascript

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 () {
    goTimer()
}, 500);

function goTimer() {
    tempTimer++;
    $("#timer").val(tempTimer);
}

But the problem is when the window/tab becomes inactive - the interval is changed to 1000ms!

When i focus the window/tab again, it changes back to 500ms.

check this out: http://jsfiddle.net/4Jw37/

Thanks a bunch.

like image 302
Avni Yayin Avatar asked May 06 '14 23:05

Avni Yayin


People also ask

Does setInterval run when tab is not active?

The timer will continue counting down even when your application's tab becomes inactive.

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

Does setInterval affect performance?

The performance of using setInterval will depend on which function you execute each interval.


1 Answers

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.

like image 127
Oriol Avatar answered Oct 04 '22 02:10

Oriol