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.


How It Works

┌─────────────────────────────────────┐
│           Event Loop                │
│  ┌─────────────────────────────┐    │
│  │      Event Queue            │    │
│  │  [Event1] [Event2] [Event3] │    │
│  └─────────────────────────────┘    │
│              ↓                      │
│  ┌─────────────────────────────┐    │
│  │   Process One Event         │    │
│  │   (run to completion)       │    │
│  └─────────────────────────────┘    │
│              ↓                      │
│         Loop back                   │
└─────────────────────────────────────┘

Key characteristics:


Example: JavaScript Event Loop

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?

  1. Synchronous code runs first (Start, End)
  2. Microtasks (Promises) run before macrotasks
  3. Macrotasks (setTimeout) run last

Event Loop vs Thread Pool

Aspect Event Loop Thread Pool
Threads Single Multiple
Overhead Low Higher (context switching)
Best for I/O-bound CPU-bound
Complexity Callback management Synchronization