الانتقال إلى المحتوى
FrontendJavaScript· 7 دقائق للقراءة

setTimeout(fn, 0) Isn't Immediate: The Event Loop, Tasks and Microtasks

A zero delay only queues a task, and every promise callback still runs before it.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

QA files a strange bug: the checkout summary sometimes logs "Charging 0". It never happens on a fresh page load, only when the coupon is already cached. The cart store collects added items in a pending list and applies them in 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

The belief: 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.

It's a fair reading of the API, and simple experiments seem to confirm it. Log something after a 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

Your page's JavaScript runs on one thread, one job at a time. MDN's execution model calls this run-to-completion: once a job starts, it can't be preempted, and nothing else runs until the call stack is empty. A script, a click handler and a timer callback are each a job that finishes before the next one begins. So setTimeout can never interrupt the code that called it, whatever the delay.

Tasks: what setTimeout queues

The repeatedly takes one runnable task and runs it. Tasks come from the platform: running a script, dispatching an event, a timer whose delay has passed. 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

Promise callbacks don't become tasks. The HTML Standard schedules promise jobs in the queue: every .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.

Here is the order for a handler that schedules both kinds:

JavaScript order.js
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");

Node 24 prints the five lines in numeric order, and the HTML Standard's processing model gives browsers the same order: the synchronous code finishes, both microtasks run (the second one was queued while the first ran), and only then does the timer's task get its turn. The timer was scheduled first and still runs last.

Rendering waits for both

Between tasks, a browser may update the rendering: run 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.

JavaScript cart.js
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 0

Both outputs come from running the files with Node. With queueMicrotask, 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.

How you schedule itWhere it waitsWhen it runs
Code in the current functionNowhere, it's runningNow, until the call stack is empty
.then, code after await, queueMicrotaskMicrotask queueAs soon as the stack is empty, before any task
setTimeout(fn, 0), setIntervalTimer task queueA later turn of the loop, when the browser picks it
click, message and other eventsThe event's task queueWhen the browser picks that task
requestAnimationFrameThe rendering updateRight before the next paint, if the browser renders

How to apply it in your project

  1. Find the zero-delay timersSearch 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.
  2. Pick the queue on purposeNeed 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.
  3. Make dependencies explicitIf 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 that checkout awaits.
  4. Test the fast pathOrdering 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.

📚 المصادر

  1. JavaScript execution model — MDN
  2. In depth: Microtasks and the JavaScript runtime environment — MDN
  3. Window: setTimeout() method — MDN
  4. HTML Standard: Event loops — WHATWG

التعليقات (0)