
setTimeout(fn, 0) Isn't Immediate: The Event Loop, Tasks and Microtasks
- كاتب موثّق
محتويات المقال
setTimeout(flush, 0), with a comment that says "right after this". On a fresh load, checkout waits for the network and the timer wins the race. On a cache hit nothing waits, and the code after await reads the total before the flush has run.
The common misconception
setTimeout(fn, 0) runs fn right after the current line, or at least before anything else that is waiting. Zero is zero, so the callback should be next in line.
setTimeout(fn, 0) and the log appears first, then fn runs a moment later, which looks like "right after". Tutorials often describe the trick as "defer until the call stack is clear", and that's half of the truth. The missing half is that the event loop has more than one queue, and promise callbacks wait in a queue that always goes first.
What actually happens
One thread, and every job runs to completion
setTimeout can never interrupt the code that called it, whatever the delay.
Tasks: what setTimeout queues
setTimeout(fn, 0) asks for a task that runs fn once 0 ms have passed. MDN puts it precisely: a delay of 0 runs in the next event cycle, not immediately. Even "next" isn't promised: the HTML Standard gives the event loop several task queues and lets the browser choose which one to serve, so a click that arrives after your timer can still run before it.
Microtasks: the queue that always goes first
.then, .catch and .finally callback, the rest of an async function after each await, and anything you pass to queueMicrotask. After every task, the event loop performs a microtask checkpoint, which runs microtasks until the queue is empty, including the ones queued along the way. Only then does it move on.
console.log("1: handler starts");setTimeout(() => console.log("5: timeout"), 0);Promise.resolve() .then(() => console.log("3: then")) .then(() => console.log("4: chained then"));console.log("2: handler ends");Rendering waits for both
requestAnimationFrame callbacks, recalculate styles and layout, and paint. It never does this in the middle of a task or while microtasks are pending, and it doesn't have to do it after every task: the spec explicitly allows a browser to run several timer callbacks back to back with no rendering in between. So setTimeout(fn, 0) doesn't even promise that the user sees anything before fn runs.
Back to the checkout bug
addItem schedules the flush as a task. checkout then awaits loadCoupon(). On a cache hit that promise is already fulfilled, so the rest of checkout is queued as a microtask, and microtasks run before any task. The console.log reads total while the flush is still sitting in the task queue. On a fresh load the coupon request takes a network round trip, and by the time it resolves the timer has long fired. The code was never correct; the network was hiding the bug.
const pending = [];let total = 0;function flush() { for (const price of pending) total += price; pending.length = 0;}function addItem(price) { if (pending.length === 0) setTimeout(flush, 0); // "right after this" pending.push(price);}const loadCoupon = async () => null; // cache hit: no network waitasync function checkout() { addItem(120); addItem(80); await loadCoupon(); console.log(`Charging ${total}`);}checkout(); // Charging 0const pending = [];let total = 0;function flush() { for (const price of pending) total += price; pending.length = 0;}function addItem(price) { if (pending.length === 0) queueMicrotask(flush); // queued before the await pending.push(price);}const loadCoupon = async () => null; // cache hit: no network waitasync function checkout() { addItem(120); addItem(80); await loadCoupon(); console.log(`Charging ${total}`);}checkout(); // Charging 200queueMicrotask, the flush joins the same queue as the await and gets there first, so it runs before checkout resumes, whether the coupon is cached or not.
.then, code after await, queueMicrotask | ||
setTimeout(fn, 0), setInterval | ||
click, message and other events | ||
requestAnimationFrame |
How to apply it in your project
Find the zero-delay timers Search for setTimeout(calls with a 0 or missing delay. For each one, write down what its author expected to run first. If the answer is "the promise code", it's a bug waiting for a cache hit.Pick the queue on purpose Need something after the current code but before anything else, like a batched state flush? Use queueMicrotask. Want input events and timers to get a turn first? Use a task, and don't assume a paint happened in between.Make dependencies explicit If code needs the flush to have happened, don't lean on queue timing at all: call flush()before reading the total, or have the store return a promise thatcheckoutawaits.Test the fast path Ordering bugs hide behind slow networks. In tests, resolve mocks immediately with Promise.resolve(data)so a microtask ordering bug fails on every run, not only on a cache hit.
Key takeaways
setTimeout(fn, 0)queues a task; it never interrupts the code that called it.After every task, all microtasks (promise callbacks, code after await,queueMicrotask) run before the next task, including the ones queued meanwhile.The browser chooses among task queues and may render between tasks, but never while microtasks are pending. "0 ms" can mean 4 ms or a full second: nested timers are clamped and background tabs are throttled. When your code depends on an order, make it explicit instead of betting on which queue wins.
التعليقات (0)