Node.js's documentation for setTimeout does not mention a minimum delay. However, the documentation for the process.nextTick function describes it as a more efficient alternative to setTimeout(fn, 0). This suggests the possibility that it's more efficient because it's avoiding this delay. Otherwise setTimeout(fn, 0) could probably be optimized to behave the same.

Does Node.js enforce a minimum delay for setTimeout, as web browsers do?

3 Answers
3

It doesn't have a minimum delay and this is actually a compatibility issue between browsers and node. Timers are completely unspecified in JavaScript (it's a DOM specification which has no use in Node and isn't even followed by browsers anyway) and node implements them simply due to how fundamental they've been in JavaScript's history and how irreplaceable they are otherwise.

Node uses libuv which a cross-platform abstraction layer for lower level system things like file-system, networking stuff, etc. One of those things is timers, which Node provides a minimal wrapper around. At the libuv level, the timers used are the system-specific high precision timers. In Windows, for example, this is implemented using QueryPerformanceFrequency and FileTimeToSystemTime which provides resolution measured in nanoseconds.

In Node, if you specify setTimeout(callback, 1) then it will be executed one millisecond later (assuming the system doesn't delay it due to be overwhelmed). In browsers, the minimum time will be 4 milliseconds as specified by the HTML5 spec: https://developer.mozilla.org/en/DOM/window.setTimeout. This isn't a guaranteed time, just a minimum. Most browsers can be expected to have a ~15ms resolution which impacts DOM animations.

One valid piece of info is that timeouts set to the same millisecond, during the same frame, will be executed in the order they were queued. If you were to do:

It should be noted that timer implementation will vary by operating system. For example, I remember a "good old" JTimer issue where the resolution of the timer was 16ms on Windows, and ~1ms on other platforms. It is almost certainly worth testing on your particular server.