tezvyn:

nextTick vs setImmediate vs setTimeout(fn, 0)

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

precise ordering of deferral mechanisms.

OUTLINE

nextTick is a microtask that drains before the loop continues; setImmediate runs in check; setTimeout(0) in timers.

WHAT THIS TESTS This probes deep familiarity with Node's deferral primitives and the difference between microtask-style and phase-based scheduling. It separates engineers who memorized buzzwords from those who can reason about ordering.

A GOOD ANSWER COVERS process.nextTick is not part of the event loop phases at all. Its callbacks run immediately after the current JavaScript operation completes, before the loop continues to the next phase, and before queued Promise reactions. Because the nextTick queue is fully drained each time, recursive nextTick calls can starve I/O entirely. setImmediate schedules a callback for the check phase, which runs right after the poll phase finishes. setTimeout with zero delay schedules for the timers phase, but the timer system clamps tiny delays, so it never truly fires in zero milliseconds.

COMMON WRONG ANSWERS Treating setImmediate and setTimeout(fn, 0) as equivalent, or claiming nextTick is just a faster setTimeout. Another error is forgetting that nextTick outranks resolved Promises in the microtask drain.

LIKELY FOLLOW-UPS Why nextTick can be dangerous, how Promise jobs interleave with nextTick, and why ordering of setImmediate versus setTimeout(0) is deterministic only when scheduled from inside an I/O callback.

ONE CONCRETE EXAMPLE Inside a fs.readFile callback, scheduling both setImmediate and setTimeout(fn, 0) reliably runs the setImmediate first, because the loop is already in the poll phase and the check phase is the very next stop, whereas the timers phase only comes around on the next iteration. At the top level of a script, however, that order can flip depending on how long process startup took relative to the timer threshold.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.