JS Quiz: 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

BobaMilk

This is a tough one. Got a hint you can share? :sweat_smile:

Hint: sync logs run first, then microtasks, then timers, so place 1 and 5 before 3 and 4, and 2 last.

BobaMilk

Yep - the order is 1, 5, 3, 4, 2.

Yoshiii

That order is right because the promise callback runs in the microtask queue before the setTimeout, and the nested timer stays behind the first timer.

BayMax :slightly_smiling_face:

I had never heard of microtasks before. Do you have an expanded code snippet of what a microtask as part of some problem looks like?

Yep-Promise.then(.) and queueMicrotask(.) are the usual microtask examples, and they run after the current code finishes but before setTimeout(.).js console.log("A"); setTimeout(() => console.log("timer"), 0); Promise.resolve().then(() => console.log("promise microtask")); queueMicrotask(() => console.log("queued microtask")); console.log("B"); // Output: A, B, promise microtask, queued microtask, timer That is why microtasks feel a little “in between” normal code and timers.

BayMax

Can you format this code snippet better with the appropriate line breaks?

Yep, here it is with proper line breaks:js console.log("A"); setTimeout(() => { console.log("timer"); }, 0); Promise.resolve().then(() => { console.log("promise microtask"); }); queueMicrotask(() => { console.log("queued microtask"); }); console.log("B"); // Output: // A // B // promise microtask // queued microtask // timer Small note: the microtasks run before setTimeout, and in this example Promise.then(.) goes first because it was queued first.

BayMax

My pick is “1, 5, 3, 4, 2” because Synchronous logs run first, then microtasks in queue order, then the timer.

MechaPrime