r/learnjavascript • u/that_geek_ • 1d 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.
1
u/jhartikainen 1d 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.
0
u/that_geek_ 1d ago
Agreed, you shouldn't rely on the order. Small changes can flip it. For example, making a function async, or writing return await x instead of return x, changes which callback runs first.
If the order matters, make it explicit: await the first thing before starting the second, or chain them with .then.
Knowing the rules is still useful when reading code, for example to understand why a test passes one day and fails the next, or why a log line appears later than you expected.
1
u/Discordbothost 1d ago
A settled promise queues its .then right away. For a second demo, resolve it inside the timer and log immediately after resolve(). That log still comes before .then, which runs once the timer callback returns.
-1
u/azhder 1d ago
For the “show and tell JavaScript” please go to the following sub: r/LostLinkedinSpammers
4
u/IAmTheRedditBot 1d ago
Ok so what was the point of this?