Question Bank
Event Loop Trace Challenge
Difficulty: Medium
Mid-tier traces of the JavaScript event loop covering microtasks, macrotasks, and the interleaving of `setTimeout`, `Promise.then`, and `queueMicrotask`. Predict every line.
Event Loop Trace Challenge
Mid-tier traces of the JavaScript event loop covering microtasks, macrotasks, and the interleaving of `setTimeout`, `Promise.then`, and `queueMicrotask`. Predict every line.
657 views
10
Trace the output line by line. State which entries are microtasks and which are macrotasks.
Examples
Example 1:
Input: console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');
Output: 1, 4, 3, 2
Explanation: Synchronous statements run first (1 then 4). When the task ends, the runtime drains the microtask queue (3) before picking the next macrotask (2). This 'microtasks before macrotasks' rule is the central event-loop invariant.Trace the output. Why does the .then after await not interleave with the synchronous prints from inner()?
Examples
Example 1:
Input: inner() logs A, awaits null, logs B; main logs start, calls inner, schedules then C, logs end
Output: start, A, end, B, C
Explanation: An async function runs synchronously up to its first await. inner() prints A then queues its continuation. The synchronous tail prints end. The microtask queue then drains FIFO: B before C because the await resumption was queued first.Order the four prints. What is the difference between queueMicrotask and Promise.resolve().then?
Examples
Example 1:
Input: setTimeout T, queueMicrotask M, Promise.resolve().then P, console.log S
Output: S, M, P, T
Explanation: queueMicrotask and Promise.resolve().then both schedule microtasks (FIFO). setTimeout is a macrotask. queueMicrotask is the lower-level primitive and is idiomatic when you do not need a Promise.Predict the output for this Python asyncio snippet. How does the asyncio loop differ from the JS event loop for the same conceptual interleaving?
Examples
Example 1:
Input: asyncio.create_task(inner()) scheduled inside main(); main prints start and end before awaiting the task
Output: start, end, A, B
Explanation: Unlike JavaScript, create_task only schedules the coroutine. The current coroutine keeps running until it itself awaits. JS's contract that an async function runs synchronously up to its first await does NOT hold in Python asyncio.Why is the following loop a hazard, and what is the correct fix to drain tasks without starving the event loop for the duration of the loop?
Examples
Example 1:
Input: synchronous while (queue.length) loop on a 1M-item queue
Output (buggy version): blocks the event loop for several seconds
Output (fixed version): drain(queue, handle, 100) yields every 100 items via setTimeout(_, 0)
Explanation: JS is single-threaded; a long synchronous loop monopolizes the event loop. The fix yields to the runtime between batches so other tasks can run.