Node.js Event Loop
Subject: Node.js
What Is the Event Loop?
The event loop in Node.js is responsible for managing asynchronous operations. It continuously monitors the callback queue and executes functions when async operations like file reads, network calls, or timers complete.
It enables Node.js to:
- Run JavaScript code
 - Perform non-blocking I/O
 - Handle thousands of tasks using a single thread
 
Why Node.js Uses the Event Loop
Traditional web servers use multithreading to manage concurrent clients. Node.js uses a single-threaded event loop, which offers:
- Lower memory usage
 - Greater scalability
 - High performance for I/O-bound operations
 
How the Event Loop Works
- Node.js executes all top-level code.
 - Async operations (e.g., 
setTimeout,fs.readFile) are offloaded to the thread pool. - When these tasks complete, their callbacks go into the callback queue.
 - The event loop checks the queue and runs the callbacks one by one.
 - Callbacks are only executed when the call stack is empty.
 
Event Loop Phases
The event loop has multiple phases that handle different types of tasks:
- Timers: Executes callbacks from 
setTimeout()andsetInterval() - Pending Callbacks: Handles specific system operations
 - Idle/Prepare: Used internally
 - Poll: Retrieves new I/O events and executes I/O callbacks
 - Check: Executes 
setImmediate()callbacks - Close Callbacks: Executes close event handlers (e.g., socket closure)
 
Event Loop in Action: Example
Output:
Explanation:
StartandEndrun immediately as synchronous code.fs.readFileis async and queues its callback after the file is read.setImmediate()executes in the check phase.setTimeout(..., 0)is scheduled in the timer phase and runs later.
Visual Representation
When Event Loop is Blocked
Blocking occurs when long-running synchronous code prevents the event loop from executing queued callbacks.
Example of Blocking:
This freezes the server, making it unresponsive.
Best Practices
- Avoid long-running synchronous code
 - Always use asynchronous APIs like 
fs.readFile,setTimeout - Use 
worker_threadsfor CPU-heavy tasks - Use 
process.nextTick()andsetImmediate()wisely 
Key Takeaways
- The event loop enables Node.js to perform async operations on a single thread
 - It manages callback queues and executes them in a specific order
 - Efficient use of the event loop results in scalable applications
 - Understanding the event loop helps avoid performance bottlenecks