Skip to content
intermediatePhase 33 · Advanced JavaScript

Event Loop

Master the event loop: call stack, web APIs, callback queue, and microtask queue.

1h
0 problems
Topic Progress0%

Event Loop Architecture

The event loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded. It continuously monitors the call stack and callback queues.

Components

  1. Call Stack: Where synchronous code executes
  2. Web APIs: Browser-provided APIs (setTimeout, fetch, DOM events)
  3. Callback Queue (Macrotask Queue): Where completed async callbacks wait
  4. Microtask Queue: Where Promise callbacks wait (higher priority)

How It Works

┌───────────────────────┐
│      Call Stack        │
│  (synchronous code)    │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│      Event Loop        │
│  (checks if stack     │
│   is empty)           │
└──────────┬────────────┘
           │
     ┌─────┴─────┐
     ▼           ▼
┌─────────┐ ┌─────────┐
│ Micro   │ │ Macro   │
│ Task    │ │ Task    │
│ Queue   │ │ Queue   │
└─────────┘ └─────────┘
console.log('1');           // Synchronous
setTimeout(() => {
  console.log('2');         // Macrotask
}, 0);
Promise.resolve().then(() => {
  console.log('3');         // Microtask
});
console.log('4');           // Synchronous

// Output: 1, 4, 3, 2

Call Stack and Web APIs

When JavaScript encounters an async operation, it delegates to the browser's Web APIs and continues executing the next line.

console.log('Start');

// setTimeout is a Web API
setTimeout(() => {
  console.log('Timeout callback');
}, 2000);

// fetch is a Web API
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

console.log('End');

Execution flow:

  1. console.log('Start') → executes immediately
  2. setTimeout → browser starts a 2-second timer, continues
  3. fetch → browser starts network request, continues
  4. console.log('End') → executes immediately
  5. After 2 seconds, timeout callback moves to macrotask queue
  6. When fetch completes, .then callback moves to microtask queue
  7. Event loop processes queues when call stack is empty

Web API Examples

  • setTimeout / setInterval
  • fetch / XMLHttpRequest
  • DOM event listeners
  • requestAnimationFrame
  • IndexedDB
  • Web Workers

Callback Queue

The callback queue (also called the task queue or macrotask queue) holds callbacks from completed async operations. The event loop pushes them to the call stack when it's empty.

// Multiple async operations
console.log('A');

setTimeout(() => {
  console.log('B'); // Macrotask 1
}, 0);

setTimeout(() => {
  console.log('C'); // Macrotask 2
}, 0);

setTimeout(() => {
  console.log('D'); // Macrotask 3
}, 0);

console.log('E');

// Output: A, E, B, C, D

Key Rules:

  1. The event loop checks if the call stack is empty
  2. If empty, it first drains all microtasks (Promises)
  3. Then it takes one macrotask from the queue
  4. Process repeats

Event Loop Cycle

// The event loop essentially does this:
while (queueIsNotEmpty) {
  // Wait for call stack to be empty
  while (callStackIsNotEmpty) {
    // do nothing
  }
  
  // First, process all microtasks
  while (microtaskQueueIsNotEmpty) {
    dequeueMicrotask();
  }
  
  // Then, process one macrotask
  dequeueMacrotask();
}

This is why microtasks (Promises) always run before macrotasks (setTimeout), even with 0 delay.

Practice Problems

0/3solved
Build Event Loop Component

Create a reusable React component implementing Event Loop. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Event Loop Testing

Write unit and integration tests for Event Loop using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Event Loop Performance

Optimize Event Loop for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is the primary purpose of the event loop?

Question 1 options

2. What is the output of this code? ```javascript console.log('1'); setTimeout(() => console.log('2'), 0); console.log('3'); ```

Question 2 options

3. Which queue does Promise.then() callback go to?

Question 3 options

4. What happens first when the event loop runs?

Question 4 options

Flashcards

Question

What is the event loop?

Answer

A mechanism that continuously monitors the call stack and callback queues, pushing callbacks to the stack when it's empty.

Question

What are Web APIs?

Answer

Browser-provided APIs (setTimeout, fetch, DOM events) that handle async operations outside the JavaScript engine.

Question

What is the difference between macrotask and microtask queues?

Answer

Microtasks (Promises) have higher priority and are all processed before the next macrotask (setTimeout) is taken.

Question

Why does setTimeout(fn, 0) not execute immediately?

Answer

The callback goes to the macrotask queue. It only runs after the call stack is empty and all microtasks are processed.

Question

What is Event Loop?

Answer

Event Loop is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.JavaScript is single-threaded but non-blocking thanks to the event loop
  • 2.Web APIs handle async operations outside the JS engine
  • 3.Microtasks (Promises) always run before macrotasks (setTimeout)
  • 4.The event loop continuously checks if the call stack is empty
  • 5.Understanding the event loop is crucial for debugging async code

Interview Tips

  • Trace through async code step by step to predict output order
  • Explain why Promise.then runs before setTimeout even with 0 delay
  • Discuss the event loop in the context of UI responsiveness
  • Compare event loop behavior in browsers vs Node.js

Cheat Sheet

Event Loop Cheat Sheet

Components

  • Call Stack: Executes synchronous code
  • Web APIs: Handle async operations (setTimeout, fetch)
  • Microtask Queue: Promise callbacks (high priority)
  • Macrotask Queue: setTimeout, setInterval callbacks

Event Loop Cycle

  1. Check if call stack is empty
  2. If empty, drain ALL microtasks
  3. Process ONE macrotask
  4. Repeat

Execution Order

  1. Synchronous code
  2. Microtasks (Promises)
  3. Macrotasks (setTimeout)

Key Insight

Even setTimeout(fn, 0) waits for microtasks to complete first.