JavaScript · Question 2 of 50
How does the event loop work? In what order do setTimeout and a Promise run?
Whether you can predict async order, and explain why a page freezes.
The answer
JavaScript runs one thing at a time on a single call stack. Timers, network and I/O are handled outside it, and their callbacks wait in queues.
When the stack is empty, the event loop first runs every microtask (promise callbacks, await continuations, queueMicrotask), then takes one macrotask (a timer, an I/O callback, a click), and repeats; the browser can paint between macrotasks. So a resolved promise always runs before setTimeout(fn, 0), and a long synchronous loop blocks everything, clicks and painting included.
console.log('A')
setTimeout(() => console.log('B'), 0)
Promise.resolve().then(() => console.log('C'))
console.log('D')
// A D C BThe picture
call stack ──empty?──▶ ALL microtasks ──▶ ONE macrotask ──▶ paint ──┐
▲ promises, await setTimeout, I/O, │
│ clicks │
└────────────────────────────────────────────────────────────────┘Why can an endless chain of promises freeze the page?
Show the answer
The microtask queue is drained completely before any macrotask or paint, so microtasks that keep queueing more never let the loop move on.