All sample questions / JavaScript
What does setTimeout(() => console.log(trace.join(' ')), 0) print? JavaScript Promises, async await and the Event Loop
Block 6, Promises, async await and the Event Loop, question 16 of the JavaScript sample
const trace = [];
trace.push('start');
setTimeout(() => trace.push('timeout'), 0);
Promise.resolve().then(() => trace.push('microtask'));
trace.push('sync-end');
setTimeout(() => console.log(trace.join(' ')), 0);
What is the exact order of the output?
Show the answer and why each option is right or wrong
Answer, C. start sync-end microtask timeout
- A. start sync-end timeout microtask
- Assumes a zero delay timer fires before the microtask queue drains. Every microtask always runs before the next macrotask, no matter how short the delay.
- B. start timeout microtask sync-end
- Assumes the timer callback preempts the rest of the current script. The synchronous code always finishes before any timer or microtask gets a turn.
- C. start sync-end microtask timeout
- Correct. The synchronous code runs to completion first, then the whole microtask queue drains, and only then does the first macrotask fire.
- D. start microtask sync-end timeout
- Assumes an already resolved promise runs its callback immediately in place. A then callback is always deferred to the microtask queue, even on a settled promise.
JavaScript finishes the current synchronous run to completion, then empties the microtask queue completely, then runs exactly one macrotask before repeating the cycle. Promise callbacks and async continuations are microtasks, while setTimeout callbacks are macrotasks, so a promise always wins the race against a timer of the same delay.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.