5 min read
•Question 23 of 62mediumHow does the Event Loop work in Node.js?
Understanding the Node.js event loop and its phases.
What You'll Learn
- How the event loop works
- Event loop phases
- Understanding async behavior
Event Loop Overview
The Event Loop is what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.
Event Loop Phases
code.jsJavaScript
┌───────────────────────────┐
┌─>│ timers │ (setTimeout, setInterval)
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ pending callbacks │ (I/O callbacks)
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ idle, prepare │ (internal use)
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ poll │ (retrieve new I/O events)
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ check │ (setImmediate)
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
└──┤ close callbacks │ (socket.on('close'))
└───────────────────────────┘Example
code.jsJavaScript
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
setImmediate(() => console.log('Immediate'));
process.nextTick(() => console.log('NextTick'));
console.log('End');
// Output: Start, End, NextTick, Timeout/ImmediateKey Points
process.nextTick()runs before event loop continuessetImmediate()runs in check phasesetTimeout(0)runs in timers phase