dev3 ·
What does this print and why?
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
#javascript#event-loop#promises
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
What does this print and why?
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
#javascript#event-loop#promises
Output: A, D, C, B.
JavaScript runs on one thread with a call stack and two main queues:
setTimeout, setInterval, I/O callbacks, UI events..then, await continuations), queueMicrotask, MutationObserver.Loop: run the current script to completion, then drain all microtasks, then (browser) maybe render, then take the next macrotask, drain microtasks again, and so on.
A logs synchronously.setTimeout schedules a macrotask. Even with 0 ms it waits for the next turn.Promise.resolve().then queues a microtask.D logs synchronously. The script ends.C.B.await is microtask basedasync function f() {
console.log(1);
await null;
console.log(3); // runs as a microtask
}
f();
console.log(2); // 1, 2, 3
setTimeout, requestIdleCallback, scheduler.yield() where supported, or Web Workers.process.nextTick (runs before promise microtasks) and setImmediate.Pitfall: setTimeout(fn, 0) is not instant; browsers clamp nested timers to at least 4 ms and timers in background tabs are throttled.