Event Loop
Exploring event loop and common implementation patterns
The mental model first
JavaScript is single-threaded. It can only do one thing at a time. But it handles async operations (timers, network calls, events) without blocking. The event loop is the mechanism that makes this possible.
There are four distinct components. Understand each one in isolation first, then understand how they interact.
Component 1: The call stack
The call stack is where synchronous code executes. It is a LIFO (last in, first out) structure. Every time a function is called, a new frame is pushed. When it returns, the frame is popped.
function c() {
console.log('c');
}
function b() {
c();
}
function a() {
b();
}
a();
Stack progression:
[a]
[a, b]
[a, b, c]
[a, b] // c returns
[a] // b returns
[] // a returns
The event loop only picks up new work when the call stack is completely empty. This is the single most important rule for understanding async execution order.
Component 2: Web APIs / Node APIs
When you call setTimeout, fetch, addEventListener, etc., you are handing work off to the browser (or Node) runtime. These run outside the JS engine, in separate threads managed by the environment. JS does not wait. It continues executing the rest of the synchronous code immediately.
console.log('1');
setTimeout(() => console.log('2'), 0);
console.log('3');
// Output: 1, 3, 2
Even with a 0ms delay, setTimeout goes to the Web API layer. Its callback only comes back after the current call stack is empty.
Component 3: Task queue (macrotask queue)
When a Web API operation completes (timer fires, event triggers, fetch resolves at the network level), its callback is placed in the task queue. Callbacks in the task queue wait until the call stack is empty, then the event loop picks up exactly one task per loop iteration.
Sources of macrotasks:
setTimeoutsetIntervalsetImmediate(Node only)- I/O callbacks
- UI rendering events
MessageChannel
Component 4: Microtask queue
The microtask queue is a separate, higher-priority queue. After every task (and after the initial synchronous script finishes), the entire microtask queue is drained before the next task is picked up. Not one microtask, all of them. And if a microtask enqueues another microtask, that new one also runs before the next task.
Sources of microtasks:
Promisecallbacks (.then,.catch,.finally)queueMicrotask()MutationObserverawait(everything after anawaitis a microtask)
The execution order rule
1. Run all synchronous code (call stack drains)
2. Drain the entire microtask queue (including any microtasks added during draining)
3. Pick one macrotask from the task queue, run it
4. Drain the entire microtask queue again
5. Repeat from step 3
This is the loop. Every single async ordering question in interviews collapses to this rule.
The foundational example
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
Walk through it:
console.log("1")- synchronous, runs immediately. Output: 1setTimeout(...)- handed to Web API, callback queued in task queue after 0ms.Promise.resolve().then(...)- Promise is already resolved,.thencallback queued in microtask queue immediately.console.log("4")- synchronous. Output: 4- Call stack empty. Drain microtask queue. Output: 3
- Pick next macrotask. Output: 2
Final output: 1, 4, 3, 2
This ordering, specifically that Promise callbacks always run before setTimeout callbacks, is the single most tested concept in JS async MCQs.
Nested microtasks: draining the full queue
Promise.resolve()
.then(() => {
console.log('microtask 1');
Promise.resolve().then(() => console.log('microtask 2'));
})
.then(() => console.log('microtask 3'));
console.log('sync');
Output: sync, microtask 1, microtask 2, microtask 3
Why not sync, microtask 1, microtask 3, microtask 2?
After the first .then runs and logs microtask 1, it enqueues a new microtask (microtask 2) and also enqueues microtask 3 (the next .then in the chain). The microtask queue at that point holds: [microtask 2, microtask 3]. They both run before any macrotask. Order within the queue is FIFO, so microtask 2 runs before microtask 3.
async/await is microtask sugar
await pauses the async function and schedules the continuation as a microtask. Everything after an await is equivalent to being inside a .then callback.
async function foo() {
console.log('foo start');
await Promise.resolve();
console.log('foo after await');
}
console.log('before foo');
foo();
console.log('after foo call');
Output: before foo, foo start, after foo call, foo after await
Walk through:
before foo- sync.foo()called. Entersfoo.foo start- sync inside foo.- Hits
await. Foo is paused. The continuation (foo after await) is scheduled as a microtask. - Control returns to the call site.
after foo call- sync. - Call stack empties. Microtask queue drains.
foo after await.
Multiple awaits: each one is a microtask checkpoint
async function run() {
console.log('A');
await null;
console.log('B');
await null;
console.log('C');
}
run();
console.log('D');
Output: A, D, B, C
After A, the first await pauses and schedules B onward as a microtask. D runs sync. Microtask fires: B runs, hits second await, schedules C. Microtask fires: C runs.
Each await is a yield point. Between each pair of consecutive statements separated by an await, other code can run.
The starvation trap: infinite microtasks
Because the microtask queue fully drains before any macrotask runs, an infinite microtask loop will starve the task queue and block rendering permanently:
function infinite() {
Promise.resolve().then(infinite); // keeps enqueuing microtasks
}
infinite();
setTimeout(() => console.log('this never runs'), 0);
setTimeout never fires. The page freezes. This is also why a synchronous infinite loop (while(true)) blocks everything, but an async loop using setInterval doesn’t: setInterval callbacks are macrotasks, and the event loop can interleave other tasks between them.
setTimeout vs setInterval vs setImmediate vs queueMicrotask
setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate')); // Node only
queueMicrotask(() => console.log('microtask'));
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
Output in Node: sync, microtask, promise, setImmediate, setTimeout
queueMicrotask and Promise .then are both microtasks, so they run before either macrotask. In Node, setImmediate runs in the check phase of the event loop, generally before setTimeout(fn, 0) callbacks when called from the main module (though the order between these two can vary depending on system timer precision when called from within I/O callbacks).
The classic interview trap: mixing all four
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve()
.then(() => {
console.log('3');
setTimeout(() => console.log('4'), 0);
})
.then(() => console.log('5'));
console.log('6');
Work through this before reading the answer.
Answer with full walkthrough
Output: 1, 6, 3, 5, 2, 4
Step by step:
1- sync.setTimeout("2")- goes to task queue.Promise.resolve().then(...)- first.thenqueued as microtask.6- sync.- Stack empty. Drain microtasks. First
.thenruns: logs3, queuessetTimeout("4")in task queue, and because this.thenresolved, queues the second.thenas a microtask. - Continue draining microtasks. Second
.thenruns: logs5. - Microtask queue empty. Pick next macrotask:
setTimeout("2"). Logs2. - Pick next macrotask:
setTimeout("4"). Logs4.
Note that 4 comes after 2 because setTimeout("4") was enqueued during the microtask phase, which happened after setTimeout("2") was already in the task queue.
Visual model to carry into interviews---
Self-test: 5 questions
Work through the output order for each one before expanding the answer.
Q1. What is the output?
console.log('A');
setTimeout(() => console.log('B'), 0);
setTimeout(() => console.log('C'), 0);
Promise.resolve().then(() => console.log('D'));
Promise.resolve().then(() => console.log('E'));
console.log('F');Answer
A, F, D, E, B, C.
Sync first: A, F. Then microtask queue drains in FIFO order: D, E. Then macrotasks one at a time: B, C.
Q2. What is the output?
async function foo() {
console.log('1');
await Promise.resolve();
console.log('2');
await Promise.resolve();
console.log('3');
}
foo();
console.log('4');Answer
1, 4, 2, 3.
foo runs sync until the first await, logs 1, then suspends. 4 runs sync. Microtask fires, foo resumes, logs 2, hits second await, suspends again. Next microtask fires, foo resumes, logs 3.
Q3. What is the output?
setTimeout(() => console.log('timeout'), 0);
Promise.resolve()
.then(() => {
console.log('p1');
return Promise.resolve();
})
.then(() => console.log('p2'));Answer
p1, p2, timeout.
The first .then logs p1 and returns Promise.resolve(). Returning a resolved Promise from a .then callback schedules the next .then as a microtask, but it takes an extra microtask tick to unwrap the returned Promise. So the queue looks like: [p1-callback] → runs, enqueues unwrap tick → [unwrap] → runs, enqueues p2 → [p2-callback] → runs. All of this happens before the macrotask queue is touched. Output: p1, p2, timeout.
Q4. True or false: if the microtask queue keeps getting new microtasks added to it, the macrotask queue will never be processed.
Answer
True. The microtask queue is fully drained after every task and after the initial script. If a microtask always enqueues another microtask, the event loop is permanently stuck draining the microtask queue. Macrotasks starve. This is also why an infinite microtask loop freezes the browser.
Q5. What is the output and why is it different from Q3?
setTimeout(() => console.log('timeout'), 0);
Promise.resolve()
.then(() => console.log('p1'))
.then(() => console.log('p2'));Answer
p1, p2, timeout. Same output, but the reason differs subtly from Q3.
Here, .then(() => console.log("p2")) is chained directly without returning a new Promise. After p1 runs, the next .then is immediately queued as a microtask (no unwrap tick needed). Both p1 and p2 complete in the microtask drain phase before timeout ever gets a chance. In Q3, returning Promise.resolve() added an extra microtask tick to unwrap it, but the end result is the same because timeout is still a macrotask waiting behind all microtasks.