In Node.js, why can setTimeout(fn, 0) and setImmediate(fn) run in either order from the main module, but not inside an fs callback?
answer
- two different loop phases
- zero delay becomes 1 ms
- is the timer due at loop start?
- check phase follows poll
basics
~20 ssetTimeout(fn, 0) is really a 1 ms timer, while setImmediate runs in the check phase right after poll. From the main module, whether 1 ms has elapsed when the loop starts decides the order; inside an I/O callback the immediate always wins.
solid answer
~50 sNode sets any delay below 1 to 1, so `setTimeout(fn, 0)` is a 1 ms timer that runs when libuv runs due timers, while `setImmediate(fn)` queues `fn` for the check phase, which libuv runs right after the poll phase. Called from the main module, both are only queued; when the loop starts it first runs any timers already due. If at least 1 ms of loop time has passed since the timer was set, the timeout fires first; if not, the loop passes through poll without blocking, runs the immediate in check, and the timeout fires afterwards. Start-up speed and machine load decide which, so the order changes between runs. Inside an I/O callback you are already in the poll phase, so check comes next and the immediate always runs before the timeout. Code should never depend on the top-level order.
code
javascript · 11 linesconst fs = require('node:fs');
// From the main module: either order is possible.
setTimeout(() => console.log('top-level timeout'), 0);
setImmediate(() => console.log('top-level immediate'));
// From an I/O callback: the immediate always runs first.
fs.readFile(__filename, () => {
setTimeout(() => console.log('io timeout'), 0);
setImmediate(() => console.log('io immediate'));
});go deeper
Remember the headline: from the main module the order of a zero timeout and an immediate is not guaranteed, and inside an I/O callback the immediate runs first.
Explain why: a zero delay becomes a 1 ms timer, immediates run in the check phase after poll, and at loop start the timer fires first only if 1 ms has already passed.
Show you would never let a test or a code path depend on the top-level order, and that you choose setImmediate deliberately when work must follow the I/O being handled.
Frame it as a team review rule: ordering assumptions between timers and immediates are flaky-test sources, so require intent-based API choice and reject tests asserting the top-level order.
## Two scheduling APIs, two different phases Node's timers and immediates look alike, but libuv runs them at different points of each **event loop iteration**: | API | Where the callback runs | Earliest it can run | |---|---|---| | `setTimeout(fn, 0)` | when libuv runs **due timers** | once 1 ms of loop time has passed | | `setImmediate(fn)` | the **check phase**, right after poll | the next check phase | | `process.nextTick(fn)` | outside the phases, after the current operation | before either of the above | The last row is only for orientation: how the tick queue and promise jobs interleave is a separate topic. This answer is about the first two rows. ## Why `setTimeout(fn, 0)` is really a 1 ms timer The `node:timers` documentation sets the rules for the `delay` argument of `setTimeout` and `setInterval`: - The default is `1`. - A delay **less than 1**, `NaN`, or **larger than `2147483647`** is set to `1`. - A non-integer delay is truncated to an integer. - Node emits a process warning for the odd cases: `TimeoutOverflowWarning` for a delay that does not fit in a 32-bit signed integer, `TimeoutNegativeWarning` for a negative number and `TimeoutNaNWarning` for a value that is not a number. A plain `0` is set to `1` without a warning. So a zero-delay timeout is a timer with a **threshold** of 1 ms. Like every Node timer, the threshold is a minimum: the callback runs at the first opportunity after it has passed, never before. ## The main-module case: a race against the clock When your main module calls both functions, nothing runs yet; both callbacks are only queued. Then the loop starts, and libuv's own design notes describe what happens next: 1. The loop updates its idea of "now". 2. It runs **due timers**: every timer whose threshold has passed by that "now". 3. It starts an iteration: pending callbacks, then **poll**. Because an immediate is waiting, poll does not block for I/O. 4. The **check phase** runs the immediate. 5. Close callbacks run, "now" is updated, and due timers run again. If loading and running your module took at least 1 ms of loop time after `setTimeout` was called, the timer is already due at step 2 and `timeout` prints first. If it took less, step 2 finds nothing due, the immediate runs at step 4 and the timeout fires at step 5. Module load time, CPU contention from other processes and the clock's resolution all move that boundary, which is why the official Node.js guide shows the same script printing both orders on two runs. The order is **non-deterministic by design**, not a bug to work around. ## Inside an I/O callback: one fixed order An `fs.readFile` callback, a socket `'data'` handler or an HTTP request handler runs during the **poll phase**. Schedule both from there and the next thing libuv does after poll is the check phase: 1. The I/O callback returns and the poll phase finishes its queue. 2. The **check phase** runs the immediate. 3. The timeout runs the next time libuv runs due timers after its 1 ms has passed. The immediate therefore runs first, however many timers are pending. That guarantee is the main reason to choose `setImmediate` over `setTimeout(fn, 0)`: it means "after the I/O being handled now, before the loop waits again", with no threshold to wait out. ```js const fs = require('node:fs'); fs.readFile(__filename, () => { setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate')); }); // Always prints: immediate, then timeout ``` ## What to take into real code - **Never depend on the top-level order.** A test that asserts it will fail now and then, typically on a loaded CI machine. - **Pick the API by intent.** Use `setImmediate` for "as soon as the loop has handled pending I/O"; use `setTimeout` when you want an actual delay. - **An immediate queued from an immediate waits a full turn.** Node runs the immediates that were queued when the check phase began; new ones wait for the next iteration, so I/O is polled in between. - **The tick queues run between callbacks.** Node drains `process.nextTick` callbacks and promise jobs between one timer callback and the next, and between one immediate and the next, not only once per phase. - **A slow callback delays both.** Neither the check phase nor the timers can start until the callback that is running returns, so a long I/O callback pushes the immediate and the timeout back together.
- If a setImmediate callback calls setImmediate again, when does the inner callback run?On the next loop iteration, not in the same check phase. Node takes the immediate queue as it stood when the check phase began and runs only that; anything queued while it runs waits until the loop has gone round again, through poll. The `node:timers` documentation states it directly: an immediate queued from inside an executing callback is not triggered until the next event loop iteration.
- What does Node do with setTimeout(fn, 3_000_000_000)?The delay is larger than `2147483647`, the largest 32-bit signed integer, so Node sets it to `1` and emits a `TimeoutOverflowWarning`. The callback runs almost at once instead of in about 35 days. For long waits, store a deadline and re-arm a shorter timer until it is reached.
- How do you get a deterministic order when both are scheduled from top-level code?Stop racing them. Either schedule one from inside the other's callback, or move both into an I/O callback, where the immediate is guaranteed to run first. Better still, choose by intent: `setImmediate` for "after pending I/O", `setTimeout` for a real delay, and do not write code whose correctness depends on the two interleaving.
- setTimeout with a 0 ms delay always runs before setImmediate in Node
- setImmediate runs at once, before the current function returns
- Timers and immediates share one queue and run in the order they were called
- The order inside an I/O callback is just as random as at top level
- A delay of 0 really means zero milliseconds in Node