How Event Loop Works in Node.js: Simple Explanation and Example
event loop in Node.js is a mechanism that allows non-blocking I/O by handling asynchronous callbacks in a single thread. It continuously checks the callback queue and executes tasks when the call stack is empty, enabling efficient concurrency without multiple threads.Syntax
The event loop itself is not a function you call directly but a built-in mechanism in Node.js that runs automatically. You interact with it indirectly by using asynchronous functions like setTimeout(), fs.readFile(), or promises.
Key parts involved:
- Call Stack: Where your code runs line by line.
- Callback Queue: Holds callbacks waiting to run after async tasks complete.
- Event Loop: Checks if the call stack is empty and moves callbacks from the queue to the stack.
setTimeout(() => { console.log('This runs after 1000ms'); }, 1000); console.log('This runs first');
Example
This example shows how Node.js runs synchronous code first, then asynchronous callbacks via the event loop.
console.log('Start'); setTimeout(() => { console.log('Timeout callback'); }, 0); console.log('End');
Common Pitfalls
Developers often expect asynchronous callbacks with setTimeout(fn, 0) to run immediately, but they run only after the current code finishes. Blocking the call stack with heavy synchronous code delays all callbacks.
Also, mixing synchronous and asynchronous code without understanding the event loop can cause unexpected order of execution.
console.log('Before blocking'); // Blocking synchronous loop const start = Date.now(); while (Date.now() - start < 2000) {} setTimeout(() => { console.log('After blocking'); }, 0); console.log('After blocking code');
Quick Reference
Event Loop Phases:
- Timers: Executes callbacks scheduled by
setTimeoutandsetInterval. - Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
- Idle, Prepare: Internal use.
- Poll: Retrieves new I/O events; executes I/O related callbacks.
- Check: Executes
setImmediatecallbacks. - Close Callbacks: Executes close event callbacks like
socket.on('close').
Understanding these helps predict callback execution order.