The event loop is a programming construct that waits for and dispatches events or messages in a program. It's fundamental to non-blocking and asynchronous programming.
┌─────────────────────────────────────┐
│ Event Loop │
│ ┌─────────────────────────────┐ │
│ │ Event Queue │ │
│ │ [Event1] [Event2] [Event3] │ │
│ └─────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────┐ │
│ │ Process One Event │ │
│ │ (run to completion) │ │
│ └─────────────────────────────┘ │
│ ↓ │
│ Loop back │
└─────────────────────────────────────┘
Key characteristics:
console.log('Start');
setTimeout(() => console.log('Timeout'), 10);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Output: Start, End, Promise, Timeout
Why this order?
Start, End)| Aspect | Event Loop | Thread Pool |
|---|---|---|
| Threads | Single | Multiple |
| Overhead | Low | Higher (context switching) |
| Best for | I/O-bound | CPU-bound |
| Complexity | Callback management | Synchronization |