The event loop is what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.
How It Works
The event loop continuously checks for pending callbacks and executes them. It has multiple phases, each handling different types of callbacks.
Event Loop Phases
- **Timers**: Executes callbacks from setTimeout and setInterval
- **Pending callbacks**: Executes I/O callbacks deferred to the next loop
- **Idle, prepare**: Used internally
- **Poll**: Retrieves new I/O events and executes callbacks
- **Check**: Executes setImmediate callbacks
- **Close callbacks**: Handles close events
Microtasks and Macrotasks
Microtasks (Promise callbacks, process.nextTick) run between event loop phases. Macrotasks (setTimeout, setInterval) run in their respective phases.
Avoiding Event Loop Blocking
Long-running synchronous operations block the event loop. Use worker threads or break up work into chunks.