Node.js
/Advanced
setImmediate()
Definition
A function that executes a callback immediately after the Event Loop's Poll phase finishes. It belongs to the Check phase of the Event Loop.
Explain Like I'm New
It's poorly named. `setImmediate` is NOT immediate. `nextTick` is immediate. `setImmediate` means: 'Hey Event Loop, after you finish dealing with all the heavy database and file operations in the Poll phase, run this code next before you loop back to the Timers.'
Real World Example
Used heavily when you have a massive array to process (like 1,000,000 items). Instead of using a `for` loop (which freezes the server), you process 1,000 items, and use `setImmediate` to process the next 1,000. This yields control back to the Event Loop, allowing it to serve HTTP requests in between chunks!
Common Use Cases
- •CPU-intensive task chunking
- •Preventing Event Loop starvation
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- Which phase of the Event Loop executes `setImmediate` callbacks?
intermediate
- What is the difference between `setImmediate` and `setTimeout(cb, 0)`?
advanced
- Why is the execution order of `setImmediate` and `setTimeout(0)` sometimes unpredictable in the main module?