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
- 1console.log('A');
- 2setTimeout(() => console.log('B'), 0);
- 3Promise.resolve().then(() => console.log('C'));
- 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
- Synchronous code on the call stack runs to completion first.
- When the stack is empty, the event loop drains the microtask queue (Promises) completely.
- 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.