Chapter 1 · The Event Loop Diner
One chef. Endless orders. Nobody waits.
Byte runs the busiest diner in town completely alone: single-threaded, like JavaScript. Yet timers, promises and clicks all get served in a precise order. Press play and watch how.
The short answer
JavaScript runs on a single thread. The event loop takes one task at a time (a script, a setTimeout callback, a click), runs it to completion, then runs every queued microtask (promise callbacks and code after await) before the next task. That's why Promise.resolve().then(...) always runs before setTimeout(..., 0).
setTimeout(0) vs Promise.then: the question every interviewer asks.
The whole file is one big order. Byte puts main() on the call stack and starts cooking.
Byte: The whole file is one big order. Byte puts main() on the call stack and starts cooking.
Swipe here or tap ▶ to step through- 1 Run the script
- 2 Stack empty?
- 3 Run every microtask
- 4 Run one task
1console.log('A: start');23setTimeout(() => {4console.log('D: timeout');5}, 0);67Promise.resolve().then(() => {8console.log('C: promise');9});1011console.log('B: end');
Nothing logged yet…
- Blue plate = a normal function call
- Purple plate = main(): the script itself
- Cream ticket = a task callback (setTimeout)
- Gold ticket = a microtask (promise, await)
- Tip: use ← → to step, drag the scene to look around.
Your turn
Predict the output
Interviewers love these. Run the story in your head, pick an answer, and see why.
What gets logged?
1 / 51console.log(1);2setTimeout(() => console.log(2));3Promise.resolve().then(() => console.log(3));4console.log(4);
Before the interview
The cheat sheet
The whole chapter in a few lines, plus the follow-up questions people get caught on.
- 1JavaScript runs on one thread with one call stack. Timers, network requests and DOM events are handled by the browser or Node and come back as callbacks.
- 2One loop turn: run the oldest task → drain all microtasks → maybe render → repeat.
- 3Microtasks:
.then/.catch/.finallycallbacks, code afterawait,queueMicrotask,MutationObserver. - 4Tasks (macrotasks):
setTimeout,setInterval, UI events,MessageChannel, I/O callbacks. - 5
setTimeout(fn, 0)means at least 0ms, never immediately. When timers are nested deeply, browsers round the delay up to about 4ms. - 6An async function runs synchronously until its first
await. Everything after it is a microtask. - 7Long tasks block clicks and rendering. Endless microtasks freeze the page. Break heavy work into chunks.
- 8In Node,
process.nextTickcallbacks run before promise microtasks, andsetImmediatecallbacks run after I/O callbacks.
Interview traps
›Is setTimeout(fn, 0) immediate?
No. It's a task, so it waits for the current script and every microtask to finish first.
›Why does Promise.then run before setTimeout?
Promise callbacks are microtasks, and the loop drains all microtasks before picking the next task.
›Where does rendering happen?
Between tasks, after microtasks drain. A long task or an endless microtask chain delays painting.
›Does await block the thread?
No. It only pauses that async function. The caller and everything else keep running.
Prefer reading?
The whole chapter, written out
Every step of every story, plus the practice questions with their answers.
The stories
›1. The classicsetTimeout(0) vs Promise.then: the question every interviewer asks.
console.log('A: start');
setTimeout(() => {
console.log('D: timeout');
}, 0);
Promise.resolve().then(() => {
console.log('C: promise');
});
console.log('B: end');- The whole file is one big order. Byte puts main() on the call stack and starts cooking.
- line 1console.log is plain synchronous code, so it goes straight onto the stack.
- line 1It prints right away and pops off. One plate at a time.
- line 3setTimeout isn't part of JavaScript itself. It's a Web API: the browser runs the timer in its own kitchen.
- line 3The callback is handed to the timer kitchen and setTimeout returns instantly. JavaScript doesn't wait around.
- line 30ms passes immediately, so the callback joins the Task Queue. It's done waiting for the timer, but now it waits for its turn.
- line 7Promise.resolve() is already fulfilled, so .then() can schedule its callback right now...
- line 7...into the Microtask Queue. Think of it as the VIP lane.
- line 11Back to synchronous code.
- line 11B prints. Neither callback has run yet, even with a 0ms timer.
- The script is finished and main() pops. The stack is empty, so the event loop finally gets to work.
- line 7Rule 1: drain the microtask queue, meaning run every microtask until it's empty. The VIP ticket goes before the timeout, even though the timeout was queued earlier.
- line 8The promise callback runs...
- line 8...and prints C.
- line 9The Microtask Queue is empty. Byte looks at the regular line.
- line 3Rule 2: take one task from the Task Queue and put it on the stack.
- line 4The timeout callback finally runs...
- line 4...and prints D.
- Everything's served: A, B, C, D. Byte keeps looping, waiting for the next order.
›2. Promise chainChained .then calls and a timer scheduled from inside a microtask.
setTimeout(() => console.log('timeout 1'), 0);
Promise.resolve()
.then(() => {
console.log('promise 1');
setTimeout(() => console.log('timeout 2'), 0);
})
.then(() => console.log('promise 2'));
console.log('sync');- A trickier order. main() goes on the stack.
- line 1First line: a timer.
- line 1The callback goes off to the timer kitchen.
- line 10ms is up. 'timeout 1' waits in the Task Queue.
- line 4The promise is already resolved, so the first .then queues its callback.
- line 4cbA joins the VIP lane.
- line 8The second .then is attached to the promise that the first .then returned. That promise is still pending...
- line 8...so cbB is not queued yet. It waits until cbA has finished.
- line 10A synchronous log.
- line 10'sync' prints first. Synchronous code always beats callbacks.
- main() pops. The stack is empty, so Byte checks the VIP lane.
- line 4Draining microtasks: cbA runs.
- line 5It logs first...
- line 5'promise 1' prints.
- line 6...then schedules another timer from inside a microtask.
- line 6Off to the timer kitchen.
- line 6It lines up behind 'timeout 1' in the Task Queue.
- line 7cbA returns, which resolves the next promise in the chain. Now cbB joins the VIP lane.
- line 8The loop is still draining microtasks, so cbB runs before any task. New microtasks jump ahead of waiting tasks.
- line 8Logging...
- line 8'promise 2' prints.
- The VIP lane is finally empty. Time for one task.
- line 1'timeout 1' has waited the longest, so it goes first.
- line 1Logging...
- line 1'timeout 1' prints.
- After every task the loop checks microtasks again. There are none, so on to the next task.
- line 6'timeout 2' runs.
- line 6Logging...
- line 6'timeout 2' prints.
- Final order: sync, promise 1, promise 2, timeout 1, timeout 2.
›3. async / awaitWhat await really pauses, and what keeps running.
async function brew() {
console.log('2: brewing');
await null;
console.log('4: served');
}
console.log('1: open');
brew();
console.log('3: next customer');- Declaring brew() doesn't run anything. Execution starts on line 7.
- line 7A synchronous log.
- line 7'1' prints.
- line 8Calling an async function runs its body synchronously, right up to the first await.
- line 2So this log runs immediately.
- line 2'2' prints. Still synchronous!
- line 3await null: brew() pauses here. The rest of the function is saved to run later.
- line 3That saved rest of brew() goes to the Microtask Queue, and brew() leaves the stack, handing back a pending promise.
- line 9Meanwhile main() keeps going.
- line 9'3' prints. The caller never waited for brew().
- The script is done and the stack is empty. Check the VIP lane.
- line 3brew() resumes right after its await.
- line 4Logging...
- line 4'4' prints.
- line 5brew() finishes and its promise resolves. Output: 1, 2, 3, 4.
Practice questions, answered
›What gets logged?
console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => console.log(3));
console.log(4);Answer: 1 4 3 2
Sync code first (1, 4). Then the stack is empty, so all microtasks drain (3). Only then does the loop take a task (2).
›queueMicrotask joins the party. What's the order?
setTimeout(() => console.log('a'), 0);
queueMicrotask(() => console.log('b'));
Promise.resolve().then(() => console.log('c'));
console.log('d');Answer: d b c a
queueMicrotask and .then share the same microtask queue, first in, first out: b then c. The timer is a task, so it goes last.
›What does await pause?
async function f() {
console.log(1);
await null;
console.log(2);
}
console.log(3);
f();
console.log(4);Answer: 3 1 4 2
f() runs synchronously until its first await (logs 1). The rest of f becomes a microtask, so 4 logs before 2.
›A microtask schedules more work. What's the order?
setTimeout(() => console.log('t1'), 0);
Promise.resolve().then(() => {
console.log('p1');
setTimeout(() => console.log('t2'), 0);
Promise.resolve().then(() => console.log('p2'));
});Answer: p1 p2 t1 t2
The loop drains microtasks until the queue is empty, including ones added during draining, so p2 runs right after p1. Then tasks run in queue order: t1, then t2.
›A .then callback keeps queuing another .then forever. What happens to the page?
function loop() {
Promise.resolve().then(loop);
}
loop();Answer: It freezes: tasks and rendering never get a turn
The microtask queue never empties, so the loop never moves on to tasks or rendering. The stack never grows (each callback finishes first), so there's no stack overflow, just a frozen tab.
Go deeper
Read and watch next
ByteTown gives you the picture. These are the sources to read when you want every detail.
- DocsJavaScript execution model (event loop)MDN ↗
- DocsUsing microtasks in JavaScript with queueMicrotask()MDN ↗
- ArticleEvent loop: microtasks and macrotasksjavascript.info ↗
- ArticleTasks, microtasks, queues and schedulesJake Archibald ↗
- VideoWhat the heck is the event loop anyway?Philip Roberts · JSConf EU ↗
- VideoIn The LoopJake Archibald · JSConf.Asia ↗
- DocsThe Node.js event loop, timers and process.nextTick()Node.js docs ↗
- SpecEvent loops (HTML Standard)WHATWG ↗
Finished the story?
Stamp it on your map. Progress is saved in this browser. Next stop: Promise Pizza Co..
Coming soon · Practice Mode
Want drills and mock interviews for this?
Join the waitlist and get early access when it opens.