JavaScript › Event Loop & Concurrency
Why does Promise.resolve().then(cb) run before setTimeout(cb, 0), even with a 0ms delay?
AdvancedAnswer
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 timeReal-world example A subtle bug where code assumed setTimeout(fn, 0) would run 'immediately after' the current synchronous code, before any promises.