Node.js Event Loop

Node.js Event Loop (Explained Simply)
The Event Loop is the heart of Node.js.
It allows Node.js to:
Handle multiple requests
Perform non-blocking I/O
Run asynchronous code
Stay single-threaded but highly scalable
The Event Loop is provided by libuv, not JavaScript itself.
Why Event Loop Exists?
JavaScript is single-threaded (one line at a time).
If it waits for slow tasks (like file read, DB call), the whole program would freeze.
Event Loop solves this by:
✔ Sending long tasks to background (libuv thread pool / OS)
✔ Running other code meanwhile
✔ Taking results back later via callbacks
How Event Loop Works (Very Simple)
Think of it like:
Event Loop Phases
Node.js Event Loop has 6 phases:
Timers Phase
Pending Callbacks Phase
Idle/Prepare Phase
Poll Phase
Check Phase
Close Callbacks Phase
Let’s explain these clearly.
1. Timers Phase
Handles callbacks of:
setTimeout()setInterval()
Example:
2. Pending Callbacks Phase
Handles errors and operations deferred by the OS.
3. Idle/Prepare Phase
Internal use (not important for developers).
4. Poll Phase (Most Important Phase!)
Here Node.js:
✔ Waits for new I/O events
✔ Executes immediate I/O callbacks
✔ Processes events like file read, network, DB queries
If poll queue is empty → it may go to timers or check phase.
5. Check Phase
Handles setImmediate() callbacks.
6. Close Callbacks Phase
Handles close events:
socket.on("close")server.close()
Microtasks (High Priority Queue)
Two microtask queues exist:
✔ Promise callbacks (.then)
✔ process.nextTick()` (highest priority)
These run between phases, before moving to the next phase.
Order of priority:
Example to Understand Event Loop Order
Output order:
Event Loop Diagram (Simple)
Why Node.js is Fast Because of Event Loop?
- No waiting for slow operations
- Uses OS & thread pool in background
- Single thread → no overhead
- Efficient I/O handling
- Can manage thousands of connections
When Event Loop is NOT Good?
CPU-heavy tasks
Example: huge loops, image processing, encryption
These block the event loop.
Solution:
Worker Threads
Child Processes
Clustering
