advertisement

Event Loop & Asynchronous JavaScript

Understand how JavaScript handles asynchronous operations using the event loop, callback queue, and microtask queue.

JavaScript is Single-Threaded

JavaScript has a single call stack, meaning it can only execute one thing at a time. But how does it handle multiple operations like network requests, timers, and user interactions?

The Answer: Event Loop

The event loop allows JavaScript to perform non-blocking operations by offloading tasks to the browser's Web APIs, then processing the results when ready.

The Event Loop

The event loop continuously checks if the call stack is empty. If it is, it takes the first task from the queue and pushes it onto the stack for execution.

Call Stack

Executes code synchronously

Web APIs

Handles async operations

Task Queues

Callbacks wait here

Task Queues

Macro Task Queue

  • setTimeout / setInterval
  • I/O operations
  • UI rendering
  • Event handlers

Micro Task Queue

  • Promise.then / catch / finally
  • queueMicrotask()
  • MutationObserver

Higher Priority!

Important Rule

Microtasks are processed before the next macrotask. The engine processes ALL microtasks before moving to the next macrotask.

Execution Order

Predict the Output
console.log('1');

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

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

console.log('4');

// Output: 1, 4, 3, 2
1 "1" logs immediately (synchronous)
2 setTimeout callback �?Macro queue
3 Promise.then �?Micro queue
4 "4" logs immediately (synchronous)
5 Microtask runs �?"3" logs
6 Macrotask runs �?"2" logs