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:

1. Take a piece of code
2. Execute it
3. If slow/async → give it to background
4. Continue with next tasks
5. When async work is done → put callback in queue
6. Event Loop picks callback → executes it

⭐ Event Loop Phases

Node.js Event Loop has 6 phases:

  1. Timers Phase

  2. Pending Callbacks Phase

  3. Idle/Prepare Phase

  4. Poll Phase

  5. Check Phase

  6. Close Callbacks Phase

Let’s explain these clearly.


1. Timers Phase

Handles callbacks of:

  • setTimeout()

  • setInterval()

Example:

Runs here.


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:

process.nextTick() (Highest)
Promise microtasks
Event Loop phases

🧪 Example to Understand Event Loop Order


 

Output order:

Start
End
NextTick
Promise
Timeout
Immediate

⭐ Event Loop Diagram (Simple)

┌─────────────────────────┐
│ JavaScript Code │
└─────────────────────────┘

┌─────────────────────────┐
│ Event Loop
├─────────────────────────┤
│ Timers │
│ Pending Callbacks │
│ Idle/Prepare
│ Poll │
Check
Close Callbacks │
└─────────────────────────┘

Executes Callbacks

 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

You may also like...