4 min read
•Question 48 of 62hardDifference between process.nextTick() and setImmediate()?
Understanding the timing differences in Node.js async callbacks.
What You'll Learn
- How each function works
- Execution order differences
- When to use which
Key Difference
| Feature | process.nextTick() | setImmediate() |
|---|---|---|
| Timing | Before event loop continues | After I/O in check phase |
| Queue | nextTick queue | Check phase queue |
| Recursion | Can block event loop | Won't block event loop |
Execution Order
code.jsJavaScript
console.log('1: Start');
setImmediate(() => console.log('2: setImmediate'));
process.nextTick(() => console.log('3: nextTick'));
Promise.resolve().then(() => console.log('4: Promise'));
console.log('5: End');
// Output:
// 1: Start
// 5: End
// 3: nextTick
// 4: Promise
// 2: setImmediatePriority Order
code.jsJavaScript
1. Synchronous code
2. process.nextTick()
3. Microtasks (Promises)
4. Macrotasks (setTimeout, setImmediate)Warning: Recursive nextTick
code.jsJavaScript
// ❌ This will block the event loop!
function recursiveNextTick() {
process.nextTick(recursiveNextTick);
}
// ✅ This won't block
function recursiveImmediate() {
setImmediate(recursiveImmediate);
}When to Use
- nextTick: Execute before any I/O, cleanup after sync code
- setImmediate: Execute after I/O, let event loop breathe