JS Quiz: Hard: Microtasks vs timers output order

What is the exact console output order?

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
queueMicrotask(() => console.log('4'));
console.log('5');
  • 1, 5, 3, 4, 2
  • 1, 3, 4, 5, 2
  • 1, 5, 4, 3, 2
  • 1, 2, 5, 3, 4
0 voters

Yoshiii

Runs 1 and 5 synchronously first, then drains microtasks (3 then 4), then the timer fires (2). So the output is 1, 5, 3, 4, 2.

The bit people mix up is Promise.then and queueMicrotask share the same microtask queue and go FIFO here, so 3 stays ahead of 4.

“1, 5, 3, 4, 2” is the order: you get the synchronous logs first, then the microtask queue drains, and only after that does the timer callback run.

Promise.then and queueMicrotask are in the same microtask queue here, so they run FIFO and 3 stays ahead of 4.

Look — that ordering’s right in browsers, but Node can surprise you once process. nextTick/setImmediate enter the chat, so people copy-paste this and then swear the universe is broken. In this exact snippet though, yeah: sync logs, then microtasks in FIFO, then the timer.