What is the Event Loop?
The Event Loop is the heart of Node.js. It’s a single-threaded loop that keeps checking: “Are there any pending tasks (like I/O, timers, callbacks)? If yes → execute them. If no → wait.”
Even though Node.js is single-threaded, it feels asynchronous because blocking I/O operations (file reading, database calls, HTTP requests) are offloaded to the operating system using the powerful libuv library.
The Complete Event Loop – Animated Explanation
Here’s the exact flow of the Node.js Event Loop (official animated diagram from Node.js team):
Watch this 30-second animation – it’s the clearest explanation you’ll ever see!
6 Main Phases of the Event Loop
- Timers → Executes setTimeout() and setInterval() callbacks that have reached their time.
- Pending Callbacks → Executes deferred I/O callbacks (mostly system-level).
- Idle, Prepare → Internal Node.js use only.
- Poll → Most important phase! Retrieves new I/O events and executes their callbacks.
- Check → Executes setImmediate() callbacks.
- Close Callbacks → Handles socket.on('close'), process.exit(), etc.
After all phases → loop repeats forever!
Real Code Examples for Each Phase
Output:
Special: process.nextTick() & Microtasks
These run immediately, before any phase!
JavaScript
Famous Interview Question
Answer depends on context!
- In main file → timeout first
- Inside I/O callback → immediate first
Final Words
The Event Loop is not magic — it’s a genius system that makes Node.js perfect for I/O-heavy apps.
Master the Event Loop = Master 80% of Node.js!
Save this post and the video – you’ll thank yourself later! 🚀
