Understanding the execution order in Node.js requires knowing how the event loop, microtasks, and macrotasks work together.
Node.js prioritizes certain callbacks before others, especially microtasks like process.nextTick() and Promises.
Basic Priority Order in Node.js
When all these are present together, the execution order generally follows this sequence:
- Synchronous code
- process.nextTick()
- Promise callbacks (.then / .catch / .finally)
- setTimeout() / setInterval() (Timers phase)
- setImmediate() (Check phase)
So the simplified order is:
Synchronous → process.nextTick → Promises → setTimeout/setInterval → setImmediate
Example
console.log("Start");
setTimeout(() => {
console.log("setTimeout");
}, 0);
setImmediate(() => {
console.log("setImmediate");
});
process.nextTick(() => {
console.log("nextTick");
});
Promise.resolve().then(() => {
console.log("promise");
});
setInterval(() => {
console.log("setInterval");
}, 0);
console.log("End");
Expected Output (Typical)
Start
End
nextTick
promise
setTimeout
setImmediate
setInterval
Explanation:
- Start / End → synchronous code runs first
- process.nextTick() → executed immediately after current operation
- Promise.then() → microtask queue runs next
- setTimeout() → executed in the Timers phase
- setImmediate() → executed in the Check phase
- setInterval() → behaves like
setTimeoutbut repeats
Why process.nextTick() Runs Before Promises
Node.js has a special Next Tick Queue.
This queue is processed before the microtask queue, which is why process.nextTick() runs before Promise callbacks.
Real Interview Tip
A clean way to explain in interviews:
- Synchronous code executes first
- Then process.nextTick()
- Then Promises (microtasks)
- Then Timers like setTimeout/setInterval
- Finally setImmediate
Important Note
The order between setTimeout(0) and setImmediate() may sometimes vary depending on the execution context (especially inside I/O callbacks). However, in most simple scripts setTimeout executes before setImmediate.
✅ Key takeaway
Node.js prioritizes microtasks (process.nextTick, Promises) before moving to event loop phases like timers and setImmediate, which ensures fast execution of critical callbacks before asynchronous tasks.