Question

I've been working on some abstractions of setTimeout and setInterval in order to process large sets of data without blocking the event loop in the browser.

Upon this, I have discovered that browsers "clamp" the number of milliseconds you specify for a timeout or an interval.

For example, if you write setTimeout('do something', 0), the browser will actually do setTimeout('do something', 4). In other words, the browser will force a minimum of 2 to 10 milliseconds, depending on which browser and version your code is running on.

This can have a big impact on the amount of time for a callback/promise to wait. There are ways around this (for timeouts, anyway), such as using postMessage or MessageChannel (poor solutions, in my opinion); they can provide the same effect as a timeout while effectively having 0 wait time.

Why do browsers clamp timeouts and intervals this way? I can find no reasoning for this, official or otherwise. My only hypothesis is that it somehow allows room other tasks to be added to the call stack, but this doesn't seem to be an issue with postMessage as far as I can tell, so beyond that I can't think of any reason why this helps anyone.

Was it helpful?

Solution

I cannot tell much about the reasons why, but following some "official" documentation that can help on your investigation of the subject.

Above all the HTML 5 Spec mentioned below may contain interesting hints to continue the investigation.

The MDN Documentation on setTimeout says:

Minimum/ maximum delay and timeout nesting

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.

In fact, 4ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the minimum timeout value for nested timeouts was 10 ms.

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here.

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

Licensed under: CC-BY-SA with attribution
scroll top