JavaScript reasoning · 1 / 4
Predict the event loop
Your challenge
Predict the output of the code below. Explain why a zero-delay timer does not run immediately.
Try it first. Write down your assumptions and explain your reasoning.
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');1.Start with the call stack
The first log runs synchronously. Registering a timer schedules later work; it does not pause the current function. The resolved promise queues a microtask. The final synchronous log runs before either queued callback.
2.Drain microtasks before the next task
After the current task finishes, the browser performs a microtask checkpoint. The promise callback therefore runs before the timer callback. The output is A, D, C, B. A timer delay is a minimum scheduling delay, not an exact execution time.
3.Explain the practical consequence
A long chain of microtasks can delay input handling and rendering. A CPU-heavy calculation still blocks the main thread even if placed inside a promise. For large computations, consider a worker; for cooperative UI work, split it into bounded chunks and allow the browser to regain control.
Take it one step further
- 1.What happens when C queues another microtask?
- 2.Why does making a function async not move computation to another thread?
Self-review
Can you explain each point without looking at the solution?
- Correct output order
- Separate tasks from microtasks
- Explain blocking and scheduling rather than claiming exact timing
