JavaScript Interview Question: How Does the Event Loop Work?
Short answer: JavaScript runs on a single thread with a call stack. Async work (timers, network, I/O) is handled by the environment, which queues callbacks. The event loop takes the next callback when the stack is empty, always draining all microtasks before the next task (macrotask).
The pieces
- Call stack - the code currently running.
- Task queue -
setTimeout,setInterval, I/O, UI events. - Microtask queue - promise callbacks (
.then,awaitcontinuations),queueMicrotask.
The classic question
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Output: 1, 4, 3, 2
1and4run synchronously on the stack.- The stack empties; all microtasks run:
3. - Then the next task: the timer callback,
2.
With async/await
async function run() {
console.log('A');
await null; // the rest of the function becomes a microtask
console.log('B');
}
run();
console.log('C');
// A, C, B
Why it matters in practice
- Long synchronous work blocks everything: clicks, rendering, other requests in Node.js.
setTimeout(fn, 0)doesn't run "immediately"; it waits for the stack and all microtasks.- In browsers, rendering happens between tasks, so a huge chain of microtasks can also delay painting.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.