Backend & Node.js · APIs, data and failure
What is process.nextTick and how does it differ from setImmediate?
Short answer
process.nextTick queues a callback on a special queue that is drained before the promise microtask queue and before the event loop continues. setImmediate runs later, in the check phase after I/O callbacks.
nextTick is not a timer and not a promise. It runs immediately after the current operation completes, before Node continues with anything else. The nextTick queue is processed before the microtask queue, and both are drained between event loop phases.
setImmediate(() => console.log("immediate"));
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");Why it exists
- Let an API finish its current operation before invoking a user callback
- Emit events or errors after the caller has had a chance to attach handlers
- Defer work until the current stack unwinds without waiting for a timer
- Guarantee ordering ahead of promise continuations when that is truly required
The danger is starvation. If a nextTick callback schedules another nextTick, the queue never empties and the event loop never reaches I/O. The same is true of a promise chain that keeps resolving itself. Use nextTick sparingly and never in a recursive pattern without a bound.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What runs first, nextTick or a promise callback?
- 2How can nextTick starve the event loop?
- 3When is setImmediate a better choice than setTimeout?
- 4Why might an API use nextTick before emitting an event?
Say it in the interview
nextTick puts a callback on a queue that drains after the current operation and before promise microtasks. setImmediate runs in the check phase, after I/O callbacks in that loop iteration. nextTick is useful when an API must not call a user callback synchronously, but recursion on nextTick can starve the event loop completely. I prefer promises or queueMicrotask unless I need the specific ordering nextTick provides.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.