JavaScript runs on a single thread, yet handles timers, network calls and clicks. Explain the event loop, including the difference between tasks (macrotasks) and microtasks. What does this code print?
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);Show hints
- Which queue does a resolved promise callback go to, and when is that queue emptied?
Show the explanation
Model answer. It prints 1, 4, 3, 2.
How it works:
- The call stack runs synchronous code to completion; nothing interrupts it.
- Slow work (timers, network, file I/O) is handed to the host (browser or Node). When it finishes, a callback is queued.
- Task (macrotask) queue:
setTimeout,setInterval, I/O callbacks and UI events. - Microtask queue: promise reactions (
.then,awaitcontinuations) andqueueMicrotask. - The event loop repeats: run one task; then run all queued microtasks (including ones added meanwhile); then the browser may render; then take the next task.
So: 1 and 4 print during the synchronous script. When the stack empties, microtasks run first (3), and only then the timer task (2), even with a 0 ms delay.
Consequences: a long synchronous loop freezes the page (no clicks, no rendering); an endless chain of microtasks can starve rendering too. Split heavy work into chunks, or move it to a Web Worker.
Original UniCircle question. Last reviewed 22 Oct 2026.
