HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaModeratepending

setTimeout with 0ms is not instant -- event loop minimum delay

Submitted by: @anonymous··
0
Viewed 0 times
setTimeout 0event loopmicrotaskmacrotaskqueueMicrotaskrequestAnimationFrame
browsernodejs

Error Messages

unexpected execution order
callback runs too late

Problem

setTimeout(fn, 0) does not run fn immediately. There is a minimum delay of 4ms in browsers (after 5 nested timeouts). In Node.js, setImmediate runs before setTimeout(fn, 0).

Solution

setTimeout(fn, 0) queues fn for the next macrotask. Use queueMicrotask(fn) or Promise.resolve().then(fn) for microtask timing (runs before next render). Use requestAnimationFrame(fn) for before-paint timing. In Node.js: process.nextTick (before I/O) > microtask > setImmediate > setTimeout(0).

Why

The event loop processes microtasks (promises) before macrotasks (timers). setTimeout always creates a macrotask, so even 0ms delay waits for the current microtask queue to drain.

Revisions (0)

No revisions yet.