What does this event-loop ordering snippet print, and why?
What does the following code print, and why?
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
Predict the output and explain.
It prints A, D, C, B. The two synchronous console.log calls run first, so A then D. The Promise.then callback is a microtask and the setTimeout callback is a macrotask; after the synchronous code finishes, all microtasks drain before any macrotask, so C prints before B even though the timeout delay is 0.
- ✗Thinking callbacks fire in source order rather than by queue type
- ✗Believing
setTimeout(…, 0)runs before pending microtasks - ✗Assuming the engine blocks on
setTimeoutor the promise inline
- →Where do
queueMicrotaskandawaitcontinuations sit in this ordering? - →Would adding a second
.thenchange whereBprints?
Solution
Synchronous code, then microtasks (promises), then macrotasks (setTimeout).
console.log('A'); // 1: synchronous
setTimeout(() => console.log('B'), 0); // macrotask
Promise.resolve().then(() => console.log('C')); // microtask
console.log('D'); // 2: synchronous
// Output: A, D, C, B
How it works
The engine first runs all synchronous code of the current task: A and D print. The setTimeout and .then callbacks are merely queued — the timer into the macrotask queue and .then into the microtask queue.
When the synchronous code finishes, the event loop fully drains the microtask queue first, so C prints. Only then does it take one macrotask, and B prints. The zero delay on setTimeout does not make it a microtask — it still waits for the microtasks to drain. </content>