What is going on here
Node runs the same JavaScript semantics as the browser but a different loop underneath. Instead of "run one task, drain microtasks", libuv walks a fixed round of phases — timers, pending callbacks, idle/prepare, poll, check, close callbacks — and each phase has its own queue of callbacks to run.
Two queues sit outside that round entirely. The nextTick queue and the promise microtask queue are drained between operations, and nextTick always goes first. That priority is the one Node-specific ordering rule worth memorising: process.nextTick beats Promise.then, and both beat every phase callback. It is also a hazard — a nextTick callback that schedules another nextTick will starve the loop completely, because the drain never ends.
setTimeout and setImmediate belong to different phases: timers and check. From the main module their relative order is genuinely nondeterministic, because it depends on how long process startup took versus the timer threshold. Inside an I/O callback the answer is stable — you are already past the timers phase, so setImmediate always wins. This scene shows the deterministic parts and the common startup case.
Common questions
What is the difference between process.nextTick and setImmediate?
They are not related despite the names. process.nextTick runs before the loop continues to any phase, ahead of promise callbacks. setImmediate queues a callback for the check phase, which runs once per loop iteration after polling for I/O.
Does process.nextTick run before a promise callback?
Yes. Node drains the nextTick queue completely before touching the promise microtask queue, so a nextTick callback always runs first even if the promise was resolved earlier.
Why is setTimeout versus setImmediate order unpredictable in Node?
From the main module the result depends on how much time process startup consumed relative to the timer threshold, so either can win. Inside an I/O callback the loop is already past the timers phase, so setImmediate reliably runs first.
Every question on one page →·Run your own code →
Embed this figure in your own post →Embed this figure
Drop this into any article or course page. It stays interactive — readers can step through it without leaving your site.