One cook, many orders
JavaScript runs one thing at a time. So how do timers, clicks and promises all get handled? The event loop: a cook who finishes the current dish, then picks the next order from the queues — in a strict order.
The order of things
- Run all the current (synchronous) code to the end.
- Run every queued microtask — promise callbacks (.then, await continuations, queueMicrotask).
- Run one task — like a setTimeout callback or a click handler.
- Repeat from step 2.
console.log("1 sync");
setTimeout(() => console.log("4 timeout (task)"), 0);
Promise.resolve().then(() => console.log("3 promise (microtask)"));
console.log("2 sync");VIP lane: Microtasks are the VIP lane: after every dish, the cook serves the entire VIP lane before taking even one regular order.