What does this event-loop snippet print?
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
This is a rite-of-passage JavaScript question because it compresses the event loop into four lines. Interviewers watch whether you reason about task queues in order instead of pattern-matching "promises are faster than timeouts". The follow-ups — timers clamping, starvation, rendering order — reveal whether you can apply the model to real asynchronous bugs.
Mental model
The event loop runs one task at a time. A task runs to completion, then the engine drains the entire microtask queue, optionally renders, and only then takes one macrotask. Repeat. Synchronous code is the first part of the current task, so it always prints before any queued callback.
Step-by-step solution
Step 1: Predict the printed order
Before running the snippet, say the order out loud. Most candidates answer A D B C, assuming promises and timers queue together, or A B C D, assuming a zero-millisecond timer fires immediately. The correct output is A D C B. The reasoning is mechanical, not mysterious. console.log('A') and console.log('D') are synchronous statements in the script's own task, so they run to completion immediately. setTimeout registers B in the macrotask queue and Promise.then registers C in the microtask queue, but neither callback can interrupt the running task. Watch the animation: A and D light up on the call-stack lane before anything moves on the microtask lane, and B waits even longer on the macrotask lane. Narrating this order in advance — sync, then all microtasks, then one macrotask — is exactly what the interviewer is listening for.
javascriptconsole.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');Step 2: Synchronous code owns the stack
The first rule of the event loop is run-to-completion: once a task starts, the engine never pauses it to run a queued callback. The entire script is a single task, so every synchronous statement executes before the engine even looks at the queues. This is why a long synchronous loop blocks timers, clicks, and painting, and why setTimeout(fn, 0) is a request to queue rather than a command to run now. In the animation, watch the call-stack lane: logging A, registering the timer, registering the promise callback, and logging D all happen inside one unbroken task. The microtask and macrotask lanes are only bookkeeping at this point; nothing queued can preempt live JavaScript. The zero-millisecond delay says nothing about when the callback runs, only about the minimum wait once the queue becomes eligible.
Step 3: The microtask queue drains
When the current task ends, the engine does not move straight to timers. It first drains the entire microtask queue to exhaustion: promise callbacks, queueMicrotask callbacks, and MutationObserver records. If a microtask queues another microtask, that new one also runs in the same drain, before the loop is allowed to proceed. This is why the code after await feels immediate — it is a microtask continuation, not a brand-new task. In the animation, C runs on the microtask lane while B still sits untouched in the macrotask lane. A promise chain that keeps rescheduling itself would keep that lane spinning and starve timers and rendering completely. The event loop escapes to a macrotask only when the microtask queue is empty, which is the rule that decides C before B in our snippet.
Step 4: One macrotask per turn
Once the microtask queue empties, the browser gets an opportunity to render, and then the loop takes exactly one macrotask — in this snippet, the timer callback B. Running B enters JavaScript as a fresh task, and anything it queues starts the cycle over: after B finishes, microtasks drain again, render may happen, and the next macrotask is selected. This one-at-a-time discipline is what keeps pages responsive; timers never batch-fire in parallel. Watch the animation: C is marked done on the microtask lane, B runs alone on the macrotask lane, a render phase appears between tasks, and the loop checks the queues again. Putting the phases together explains the output: the script prints A and D synchronously, the microtask queue prints C, and the first macrotask prints B.
Step 5: Where this breaks in practice
The mental model gets subtle in real code. Browsers clamp nested setTimeout(0) calls to roughly four milliseconds after five levels, so a "zero" timer is never truly immediate and can interleave with rendering. An unbounded await loop that keeps queueing microtasks starves timers and painting, freezing the tab. Awaiting an already-resolved promise still suspends and resumes through the microtask queue — the async variant below prints A D C B exactly like the .then version, because the post-await continuation is itself a microtask. In Node, process.nextTick runs before promise microtasks and setImmediate lands in the check phase rather than the timer phase. Watch the final animation: the microtask lane keeps refilling instead of draining, the render lane never activates, and the timer waits forever. That picture is microtask starvation, and it is the root cause behind many "the UI froze" bug reports. Yield to a macrotask periodically in long async loops.
javascriptasync function main() { console.log('A'); await Promise.resolve(); console.log('C'); // microtask continuation } main(); setTimeout(() => console.log('B'), 0); console.log('D'); // prints: A D C B
Edge cases & traps
- Assuming setTimeout(fn, 0) is immediate: browsers clamp nested timers to about 4 ms, so use queueMicrotask or MessageChannel when you truly need to yield immediately.
- Forgetting that code after await is a microtask: an async continuation still runs before any timer callback.
- Treating Node and browsers as identical: process.nextTick beats promise microtasks in Node, and setImmediate runs in the check phase, not the timer phase.
- Starving the loop with a promise chain that reschedules itself: insert a macrotask yield so rendering and timers can run.
- Calling requestAnimationFrame a microtask: rAF is a render-phase callback that fires before the next paint, not a microtask; relative to a timer it fires at the next render opportunity — never between synchronous code and the microtask queue.