🔹 setImmediate() in JavaScript
setImmediate() is a Node.js-specific function that schedules a callback to run after the current poll phase of the event loop, but before any I/O or timers.
✅ Syntax:
setImmediate(() => {
console.log("This runs in the check phase of the event loop");
});
🔹 process.nextTick()
process.nextTick() schedules a callback to be invoked immediately after the current operation completes, before any other I/O events, timers, or setImmediate().
process.nextTick(() => {
console.log("Runs before setImmediate and setTimeout");
});
⚔️ Key Differences between setImmediate() and process.nextTick():
- Execution Timing:
process.nextTick()runs before the event loop continues (within the same phase).setImmediate()runs on the check phase, after I/O events are processed.
- Use Case:
- Use
process.nextTick()for short, immediate tasks (microtasks). - Use
setImmediate()for deferring execution until the end of the event loop cycle (macrotasks).
- Use
- Risk:
- Too many
nextTick()calls can starve the event loop (since they run before anything else).
- Too many
🔧 Example:
console.log("Start");
process.nextTick(() => {
console.log("Next tick");
});
setImmediate(() => {
console.log("Set Immediate");
});
console.log("End");
📤 Output:
Start
End
Next tick
Set Immediate