JavaScript · Lesson 17 of 20 · 4 min
Event Loop, Microtasks & Macrotasks
This is the most common advanced JS topic. Nail this, and you prove you understand how async JS actually works under the hood.
JavaScript is single-threaded. One call stack, one thing at a time. Yet we handle multiple operations concurrently. The event loop is the mechanism that makes this possible without true parallelism. It’s a scheduler that decides what code to run next.
Your job in an interview is to demonstrate you understand this scheduler's rules, especially its strict priority system.
The Two Queues: VIP vs. General Admission
When an async operation finishes (e.g., a timer fires, a fetch completes), its callback doesn't run immediately. It's placed in one of two queues.
The Macrotask Queue (or "Task Queue") is for general admission.
setTimeout,setInterval- I/O operations (network requests, file system)
- UI events (
click,scroll) requestAnimationFrame(a special case, but think of it here)
The Microtask Queue is the VIP list. It gets processed first.
Promise.then(),.catch(),.finally()await(the code after anawaitis scheduled as a microtask)queueMicrotask()MutationObserver
The rule is simple and absolute: after the main script finishes and the call stack is empty, the event loop will run all tasks in the microtask queue to completion. Only after the microtask queue is completely empty will it process one task from the macrotask queue.
This cycle repeats forever.
How to Trace Execution Order
The interview question: You'll be given a code snippet with a mix of
console.log,setTimeout, andPromise.then. Your job is to trace the execution and state the output. Don't just give the answer; explain the 'why' for each step, referencing the queues.
Let’s trace this common example.
console.log('A. Script start');
setTimeout(() => {
console.log('F. Macrotask 1 (setTimeout)');
Promise.resolve().then(() => {
console.log('G. Microtask inside Macrotask');
});
}, 0);
setTimeout(() => {
console.log('H. Macrotask 2 (setTimeout)');
}, 0);
Promise.resolve().then(() => {
console.log('C. Microtask 1');
Promise.resolve().then(() => {
console.log('D. Microtask 2 (nested)');
});
});
queueMicrotask(() => {
console.log('E. Microtask 3');
});
console.log('B. Script end');
Here's the play-by-play:
-
Synchronous Pass: The engine executes the script top to bottom.
console.log('A. Script start')runs. Output:A. Script start.setTimeoutis a Web API. Its callbackFis sent to the macrotask queue.- The second
setTimeoutsends its callbackHto the macrotask queue. Promise.resolve().then()sends callbackCto the microtask queue.queueMicrotask()sends callbackEto the microtask queue.console.log('B. Script end')runs. Output:B. Script end.
-
Microtask Drain: The main script is done. The call stack is empty. The event loop checks the microtask queue. It is not empty.
- It pulls
Cand runs it. Output:C. Microtask 1. - Inside
C, anotherPromise.then()is found. Its callbackDis added to the end of the microtask queue. - The loop continues. It pulls
Eand runs it. Output:E. Microtask 3. - The loop continues. It pulls
Dand runs it. Output:D. Microtask 2 (nested). - The microtask queue is now empty.
- It pulls
-
Macrotask Turn: The event loop now picks just one task from the macrotask queue.
- It pulls
Fand runs it. Output:F. Macrotask 1 (setTimeout). - Inside
F, aPromise.then()is found. Its callbackGis added to the microtask queue. - The macrotask
Ffinishes. The call stack is empty.
- It pulls
-
Microtask Drain (Again): Before starting the next macrotask, the loop must check for microtasks again.
- It finds
Gand runs it. Output:G. Microtask inside Macrotask. - The microtask queue is empty again.
- It finds
-
Next Macrotask: The loop picks the next macrotask.
- It pulls
Hand runs it. Output:H. Macrotask 2 (setTimeout).
- It pulls
Final output: A, B, C, E, D, F, G, H.
The trap: Candidates often forget that a new microtask scheduled inside another microtask runs before any macrotasks. They also forget that a microtask scheduled inside a macrotask runs before the next macrotask.
The Diagram That Explains the Cycle
This flow chart shows the decision-making process of the event loop. The key is the "Drain ALL Microtasks" step that happens after any chunk of JS finishes and before the next macrotask is considered.
Why This Blocks Your UI
The priority system has a direct impact on performance. Because the microtask queue is drained completely, you can block everything else.
Consider an infinite microtask loop:
Promise.resolve().then(function loop() {
// This will run forever
Promise.resolve().then(loop);
});
This code will completely starve the macrotask queue. No setTimeout will ever run. No user clicks will ever be handled. The page will be frozen.
A more realistic problem is a long-running synchronous operation inside a microtask. If a Promise.then callback performs a heavy calculation that takes 200ms, the browser is completely locked for that duration. It cannot render updates or respond to input, because it's stuck in the "Drain Microtasks" phase.
Use macrotasks (setTimeout(fn, 0)) to yield to the browser, allowing it to render and handle other tasks before your code runs. Use microtasks only for quick, high-priority work that must happen immediately after the current script.
Try it
Take the main code example from the "How to Trace Execution Order" section. Manually write down the state of the microtask and macrotask queues after each line of the initial script runs. Then, trace the execution step-by-step on paper, predicting the output. Finally, run the code in your browser's console to verify your trace. This 15-minute exercise solidifies the entire model.
Next: We'll apply these concepts when we start Working with the DOM, where events and rendering are managed by this same loop.
Lock it in — apply this lesson under interview conditions.