How does the JavaScript Event Loop work?

JavaScript is single-threaded, yet code written with setTimeout and Promises seems to run "at the same time". The mechanism behind this is the event loop.

Example code

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

Expected output: A, D, C, B. Follow it step by step in the animation below.

Event loop animation: how code with console.log, setTimeout and a Promise runs step by step through the call stack, Web APIs, and the microtask and macrotask queues. The output order is A, D, C, B.

Code

  1. 1console.log('A');
  2. 2setTimeout(() => console.log('B'), 0);
  3. 3Promise.resolve().then(() => console.log('C'));
  4. 4console.log('D');

Call stack

main()

Web APIs

Microtask queue

Macrotask queue

Event loop
Running

Console

—

The program starts and the global code enters the stack.

Step 1 / 17

Rules in short

  1. Synchronous code on the call stack runs to completion first.
  2. When the stack is empty, the event loop drains the microtask queue (Promises) completely.
  3. Then it takes one task from the macrotask queue (setTimeout) and repeats.

That is why, even with setTimeout(..., 0), B is printed after C, the Promise callback.