Understanding Node.js Event Loop: A Complete Guide
Deep dive into how the Node.js event loop works, including phases, timers, and microtasks.
The Node.js event loop is one of the most important concepts to understand when working with Node.js. It's what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.
What is the Event Loop?
The event loop is what allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.
Event Loop Phases
The event loop has several phases, each with a FIFO queue of callbacks to execute:
1. **Timers Phase**: Executes callbacks scheduled by setTimeout() and setInterval() 2. **Pending Callbacks**: Executes I/O callbacks deferred to the next loop iteration 3. **Idle, Prepare**: Used internally 4. **Poll Phase**: Retrieves new I/O events and executes I/O related callbacks 5. **Check Phase**: setImmediate() callbacks are invoked here 6. **Close Callbacks**: Executes close callbacks like socket.on('close')
How It Works
When Node.js starts, it initializes the event loop and processes the provided input script. The script may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.