The Event Loop is the mechanism that allows Node.js (single-threaded) to handle multiple operations concurrently without blocking.
It continuously checks for tasks and executes them in a specific order using queues and phases.
process.nextTick- Promises (
.then) - Then event loop phases
- Current code execution
- process.nextTick queue (Not part of Event Loop)
- Promise (microtask queue, Part of Event Loop, executes between each phase of event loop)
- Event loop phases (timers → poll → check → ...)
Why We need Event Loop:
Node.js runs on one main thread, so it cannot do multiple things at the exact same time.
Instead:
- It offloads heavy work (I/O, network, DB) to OS / libuv
- Uses the event loop to process completed tasks
Event Loop Phases:
- Timers
- Pending Callbacks
- Poll (I/O)
- Check
- Close Callbacks
It executes callbacks of timers whose delay has already expired.
Node.js does NOT execute it immediately
Instead:
- Registers the timer with libuv (timer system)
- Keeps track of when it should expire
After ~1000ms:
- Timer becomes “ready”
- Its callback is placed in the Timers queue
Event loop enters Timers phase
- It checks: “Which timers have expired?”
- Executes their callbacks
Timer registered (libuv)
↓
Time passes
↓
Timer expires → added to timers queue
↓
Event loop enters Timers phase
↓
Callback executed
setTimeout(fn, 0) is NOT immediate?setTimeout(fn, 0) does not execute immediately because the callback is scheduled and only runs when the event loop reaches the timers phase after the current execution completes.console.log("B");
A
Main Thread sends setTimeout(() => console.log("A"), 0); to run with libuv thread pool
setTimeout and setInterval register timers with the system. Once their delay expires, their callbacks are queued and executed during the Timers phase of the event loop, not immediately.2. Pending Callbacks:
while Poll phase handles new I/O events and executes most I/O callbacks.
Executes callbacks that were deferred from the previous event loop iteration
- Some TCP errors (like
ECONNREFUSED) - System-level I/O errors
- Low-level libuv deferred callbacks
These are not your regular fs.readFile or DB call or HTTP callbacks.
Something happened earlier, but couldn’t be processed immediately → now handled here
Important:
- Rarely used directly in application code
- Mostly internal to Node.js
Mostly all developer written code execute (or handled callbacks) from here.
- Execute I/O callbacks:
- File system (fs.readFile)
- Network (HTTP, DB calls)
- Wait for new I/O events if none are ready
Example
-
You call
fs.readFile() or any DB call or any API call - OS processes it
- Result comes back
Callback runs in Poll phase
4. Check Phase
Runs after Poll phase
Executes: setImmediate()
5. Close Callbacks
The Close Callbacks phase executes callbacks related to resource cleanup, especially when a handle (like a socket or stream) is closed.
When something like:
- a socket
- a stream
- a connection
gets closed or destroyed, its cleanup callback runs here.
Executes: socket.on('close'), cleanup tasks
No comments:
Post a Comment