Advertisement
Advanced JavaScript, Event Loop & Concurrency

Why does Promise.resolve().then(cb) run before setTimeout(cb, 0), even with a 0ms delay?

Short answer

setTimeout(fn, 0) doesn't run immediately — it's still scheduled as a macrotask, which the browser also clamps to a minimum delay (often ~4ms after nesting).

Save JavaScript mock interview
Advertisement
AModel answer
setTimeout(fn, 0) doesn't run immediately — it's still scheduled as a macrotask, which the browser also clamps to a minimum delay (often ~4ms after nesting). Promise callbacks are microtasks, and ALL pending microtasks are drained before the event loop even considers the next macrotask.
setTimeout(() => console.log('macro'), 0);
Promise.resolve().then(() => console.log('micro'));
// logs: 'micro' then 'macro', every time
Real-world example
A subtle bug where code assumed setTimeout(fn, 0) would run 'immediately after' the current synchronous code, before any promises.
Likely follow-ups
  • Is there any way to schedule work that runs before all microtasks?
Related topics