Frontend System Design · Lesson 9 of 86 · 5 min
Event Loop: Call Stack, Task and Microtask Queues
This is how you nail the "predict the console output" questions that test your core understanding of async JavaScript.
When an interviewer asks you to trace a mix of setTimeout, Promises, and console.log statements, they aren't testing your memory. They're testing your mental model of how JavaScript, a single-threaded language, handles concurrency. Get this right, and you signal a deep understanding of the browser's runtime.
The Single Thread and Its Limits
JavaScript has one call stack. This means it can only do one thing at a time. If you run a function that takes 500ms to complete, nothing else happens for 500ms. The browser can't respond to clicks, it can't rerender the page, it's frozen. This is called "blocking the main thread."
The call stack is a simple LIFO (Last-In, First-Out) queue. When you call a function, it's pushed onto the stack. When it returns, it's popped off. All your synchronous code runs here.
To avoid blocking, the browser gives you Web APIs like setTimeout or fetch. When you call one, the browser offloads the work from the call stack and handles it elsewhere. When the work is done (the timer finishes, the network request completes), the callback function you provided doesn't just jump back into your code. It's placed in a queue, waiting for its turn.
The Two Queues: Task vs. Microtask
There isn't just one queue; there are two, with a strict priority system. This priority is the most common source of confusion and the number one thing interviewers test.
Task Queue (or Macrotask Queue): This is the lower-priority queue. It holds callbacks for events like setTimeout, setInterval, I/O operations, and user interactions (clicks, scrolls).
Microtask Queue: This is the high-priority queue. It holds callbacks for Promises (.then(), .catch(), .finally()), queueMicrotask(), and MutationObserver.
The distinction is critical. Microtasks are for work that needs to happen immediately after the current script finishes, but before the browser does anything else, like rendering or running the next task.
The Rules of Execution
The Event Loop is the orchestrator that decides what code to run next. It has one simple, repeating job.
The trap: Candidates often describe the event loop as "when the call stack is empty, move something from a queue." That's too simple. The real algorithm is what separates a junior from a senior answer.
Here is the precise logic, in order:
- Run synchronous code until the call stack is empty.
- Check the Microtask Queue. Are there any microtasks?
- If yes, pull every single microtask from the queue and execute them one by one until the queue is empty. If new microtasks are added during this process, they are also executed before moving on.
- Only when the Microtask Queue is completely empty, check the Task Queue.
- If there's a task, pull just one task from the queue and execute it.
- After that single task finishes, go back to step 2 and check for microtasks again.
This cycle—run one task, then drain the microtask queue—is the core of it all.
Trace This Code: A Common Interview Problem
You will be given a snippet like this and asked for the output. Don't guess. Trace the execution using the rules above.
console.log('A. Script start');
setTimeout(() => {
console.log('F. setTimeout 1 (Task)');
Promise.resolve().then(() => {
console.log('G. Promise in setTimeout (Microtask)');
});
}, 0);
Promise.resolve().then(() => {
console.log('C. Promise 1 (Microtask)');
setTimeout(() => {
console.log('E. setTimeout in Promise (Task)');
}, 0);
});
Promise.resolve().then(() => {
console.log('D. Promise 2 (Microtask)');
});
setTimeout(() => {
console.log('H. setTimeout 2 (Task)');
}, 0);
console.log('B. Script end');
Let's trace it step-by-step:
-
Synchronous Pass:
console.log('A. Script start')runs. Output:A. Script start.setTimeoutforFis found. Its callback is sent to the Web APIs.Promise.resolve().then()forCis found. Its callback is placed in the Microtask Queue.Promise.resolve().then()forDis found. Its callback is placed in the Microtask Queue.setTimeoutforHis found. Its callback is sent to the Web APIs.console.log('B. Script end')runs. Output:B. Script end.- The Web API timers for
FandHexpire immediately and their callbacks are placed in the Task Queue. The order is preserved:FthenH. - The initial script is done. The call stack is empty.
-
Event Loop: Microtask Check:
- The Event Loop sees the Microtask Queue has items (
C, thenD). - It executes
C. Output:C. Promise 1 (Microtask). - Inside
C, asetTimeoutforEis found. Its callback is sent to Web APIs, which then places it in the Task Queue afterFandH. - It executes
D. Output:D. Promise 2 (Microtask). - The Microtask Queue is now empty.
- The Event Loop sees the Microtask Queue has items (
-
Event Loop: Task Check:
- The Event Loop sees the Task Queue has items (
F,H,E). - It pulls one task:
F. - It executes
F. Output:F. setTimeout 1 (Task). - Inside
F,Promise.resolve().then()forGis found. Its callback is placed in the Microtask Queue. - Task
Fis finished.
- The Event Loop sees the Task Queue has items (
-
Event Loop: Microtask Check (again):
- Before checking for the next task, the loop must check for microtasks. It finds
G. - It executes
G. Output:G. Promise in setTimeout (Microtask). - The Microtask Queue is now empty.
- Before checking for the next task, the loop must check for microtasks. It finds
-
Event Loop: Task Check:
- The Event Loop sees the Task Queue has items (
H,E). - It pulls one task:
H. - It executes
H. Output:H. setTimeout 2 (Task). - Task
His finished.
- The Event Loop sees the Task Queue has items (
-
Event Loop: Microtask Check:
- The Microtask Queue is empty.
-
Event Loop: Task Check:
- The Event Loop sees the Task Queue has one item (
E). - It pulls
E. - It executes
E. Output:E. setTimeout in Promise (Task). - Task
Eis finished.
- The Event Loop sees the Task Queue has one item (
Final Output:
A. Script start
B. Script end
C. Promise 1 (Microtask)
D. Promise 2 (Microtask)
F. setTimeout 1 (Task)
G. Promise in setTimeout (Microtask)
H. setTimeout 2 (Task)
E. setTimeout in Promise (Task)
The key is realizing that microtask G runs before tasks H and E, even though H and E were queued earlier. This is because the microtask queue is checked after every task.
Try it
Take the code example from the last section. Change the first Promise.resolve().then(...) to new Promise(res => setTimeout(res, 0)).then(...). Predict the new output, then run the code in your browser console to verify. Think about why moving the promise resolution into a setTimeout (a task) dramatically changes the execution order.
Next: We'll see how async/await is syntactic sugar over Promises, using this same microtask system to make async code easier to read and write in Async JavaScript: Promises and async/await.
Lock it in — apply this lesson under interview conditions.