What is the difference between process.nextTick and setImmediate
· Category: Node.js
Short answer
process.nextTick callbacks execute immediately after the current operation and before the event loop continues. setImmediate callbacks execute on the next iteration of the check phase. In practice, nextTick always runs before setImmediate.
Details
Node.js divides the event loop into phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks. process.nextTick and microtasks (Promises) form a separate queue that drains after each C++ phase transition, making them the highest priority async operations. Overusing nextTick can starve the event loop, causing I/O starvation.
setImmediate fires during the check phase, after polling for I/O. It is the closest Node.js equivalent to setTimeout(..., 0) but runs after I/O events. For a broader look at async patterns, see what is the JavaScript event loop and how does it work. If you are writing async initialization code, how to use async/await keeps the syntax clean.
Tips
- Prefer
setImmediateoverprocess.nextTickin library code to avoid surprising consumers with prioritized execution. - Never perform heavy computation in a
nextTickcallback because it blocks I/O from proceeding. - For error handling in scheduled callbacks, review how to handle errors with try-catch to avoid unhandled exceptions.