r/learnjavascript • • 17m ago

Why does setTimeout(fn, 0) run after a promise callback? I made a step-by-step visualizer to show it

The short answer: promise callbacks are microtasks, and the event loop empties the microtask queue as soon as the call stack is empty, before it takes the next task (like a timer callback).

console.log("1: script start");

setTimeout(function timer() {
  console.log("5: timeout");
}, 0);

Promise.resolve().then(function onResolved() {
  console.log("3: then");
});

queueMicrotask(function micro() {
  console.log("4: microtask");
});

console.log("2: script end");

Output: 1, 2, 3, 4, 5. If you want to watch it happen step by step, I built a free visualizer that shows the call stack and both queues for any snippet you paste, with an explanation for every step: https://jshunt.dev/tools/javascript-event-loop-visualizer

Happy to answer questions about any snippet that confuses you.

0 Upvotes

3 comments sorted by

3

u/IAmTheRedditBot 16m ago

Ok so what was the point of this?

1

u/azhder 6m ago

For the “show and tell JavaScript” please go to the following sub: r/LostLinkedinSpammers

0

u/jhartikainen 10m ago

While it's useful to know this, I think it's best to not assume any particular ordering.

If your async logic assumes it runs in a particular order, that's a really quick way to get bugs that only reproduce in some annoying edgecase.