How does the Event Loop work?

The Event Loop is a fundamental concept in JavaScript that handles asynchronous operations and callback execution. It's what allows JavaScript to be non-blocking despite being single-threaded.

Key Components

  • Call Stack - Executes synchronous code
  • Web APIs - Handles async operations (setTimeout, fetch, etc.)
  • Callback Queue - Stores callbacks ready for execution
  • Microtask Queue - Higher priority queue for Promises
  • Event Loop - Coordinates between these components

Example

console.log('Start');

setTimeout(() => {
  console.log('Timeout 1');
}, 0);

Promise.resolve()
  .then(() => console.log('Promise 1'));

setTimeout(() => {
  console.log('Timeout 2');
}, 0);

console.log('End');

// Output:
// Start
// End
// Promise 1
// Timeout 1
// Timeout 2

How It Works

  1. Synchronous code executes immediately on the call stack
  2. Async operations are delegated to Web APIs
  3. Completed async operations push callbacks to appropriate queues
  4. Event loop checks if call stack is empty
  5. If empty, processes microtasks first (Promises)
  6. Then processes macrotasks (setTimeout, setInterval)

Common Interview Follow-up Questions

  1. Why do microtasks have priority over macrotasks?
  2. How does this affect performance in web applications?
  3. What's the difference between setTimeout(fn, 0) and setImmediate()?
  4. How does the event loop differ in Node.js vs browsers?

Best Practices

  • Avoid blocking the event loop with long-running tasks
  • Use microtasks judiciously to prevent starving macrotasks
  • Consider using Web Workers for CPU-intensive tasks
  • Be aware of how different async operations are prioritized