JavaScript
/Advanced
Event Loop Deep Dive
Definition
A highly granular look at the Node.js Event Loop phases: Timers, Pending Callbacks, Idle/Prepare, Poll, Check, and Close Callbacks.
Explain Like I'm New
The browser Event Loop is fairly simple. The Node.js Event Loop is a giant factory with 6 different conveyor belts (phases). The manager (Event Loop) walks to belt 1, processes everything, walks to belt 2, processes everything, and repeats the circle. `setTimeout` goes on belt 1. File reading goes on belt 4. `setImmediate` goes on belt 5.
Real World Example
Understanding why `setImmediate` might fire BEFORE a `setTimeout(cb, 0)` depending on whether they were called from the global script or inside an I/O callback.
Common Use Cases
- •Node.js server optimization
- •Predicting complex async execution order
Terminal Output
bash / terminal
const fs = require('fs');
// 1. Drains first, before the Event Loop even continues
process.nextTick(() => console.log('nextTick 1'));
// 2. Microtask, drains after nextTick
Promise.resolve().then(() => console.log('Promise 1'));
// 3. Timers phase
setTimeout(() => console.log('setTimeout 1'), 0);
// 4. Check phase
setImmediate(() => console.log('setImmediate 1'));
// Output order (Usually):
// nextTick 1
// Promise 1
// setTimeout 1 (Non-deterministic vs immediate in main module)
// setImmediate 1
Interview Questions
basic
- What are the main phases of the Node.js Event Loop?
intermediate
- What is the difference between `process.nextTick()` and `setImmediate()`?
advanced
- If you call `setTimeout(cb, 0)` and `setImmediate(cb)` in the main module, which runs first?