The JavaScript Event Loop — How Async Code Actually Works
The Interview Question
Explain how the JavaScript event loop works. What's the difference between the task queue and the microtask queue?
Expert Answer
JavaScript is single-threaded — it has one call stack and can execute one piece of code at a time. The event loop is the mechanism that lets it handle asynchronous operations without blocking. Here's the cycle: the call stack executes synchronous code. When it encounters an async operation (setTimeout, fetch, DOM event), it delegates it to the browser/Node.js runtime and continues. When the async operation completes, its callback is placed in a queue. There are two queues: the macrotask queue (setTimeout, setInterval, I/O) and the microtask queue (Promise.then, queueMicrotask, MutationObserver). The critical rule: after every task completes and the call stack is empty, the event loop drains the ENTIRE microtask queue before picking up the next macrotask. This means promises always resolve before the next setTimeout, even if the setTimeout was registered first.
Key Points to Hit in Your Answer
- Single thread, one call stack — async is handled by the runtime environment
- Microtasks (Promises) are processed before macrotasks (setTimeout)
- The entire microtask queue is drained before the next macrotask runs
- Microtasks can queue more microtasks, potentially starving macrotasks
- requestAnimationFrame runs before the next paint, after microtasks
- Node.js has additional phases: timers, poll, check (setImmediate)
Code Example
// Classic interview question — predict the output
console.log('1'); // sync
setTimeout(() => console.log('2'), 0); // macrotask
Promise.resolve().then(() => {
console.log('3'); // microtask
Promise.resolve().then(() => {
console.log('4'); // microtask (queued by microtask)
});
});
console.log('5'); // sync
// Output: 1, 5, 3, 4, 2
// Sync first (1, 5), then all microtasks (3, 4), then macrotask (2)
What Interviewers Are Really Looking For
The 'predict the output' format is extremely common. Walk through the execution step by step: sync code first, then microtasks, then macrotasks. If you can explain why a Promise.then inside another Promise.then runs before setTimeout(0), you've nailed it. Mentioning requestAnimationFrame's timing shows browser knowledge.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →