When you're nesting setTimeout(f, 0)
calls, your browser will silently increase the delay to 5 milliseconds after the fourth level of nesting.
This is called "timeout clamping" and defined in the HTML spec Show archive.org snapshot :
If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
Timeouts are clamped harder in background tabs
On a similar note, all major browsers have implemented throttling rules for setInterval
and setTimeout
calls from tabs that are currently in the background. You can test it yourself by running the test below and change to a different tab during its runtime. The expected runtime drastically increases in Chrome, Firefox and Safari:
https://testbed.nicon.nl/timeouttest/
Show archive.org snapshot
See also: Stop animations and network polling when the document tab isn't visible
Measuring timeout clamping
Here is a deeply nested setTimeout
call:
var start = Date.now();
function printElapsed() {
var now = Date.now();
console.log(now - start);
}
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
setTimeout(function() {
printElapsed();
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
}, 0);
This yields the following messages:
2
3
5
6
11
16
20
25
29
33
38
Observe how after 6
the time difference jumps from 2 to 5 milliseconds.