Event Loop and Microtasks
Describe the browser/Node event loop: call stack, macrotasks, and microtasks (Promises). What prints first in setTimeout(0) vs Promise.then?
Answers use simple, clear English.
Quick interview answer
JS runs on a single call stack. After stack clears, microtasks (Promise jobs, queueMicrotask) run before the next macrotask (setTimeout, I/O, setImmediate quirks). Therefore Promise.then callbacks usually run before setTimeout(0).
Detailed answer
JS runs on a single call stack. After stack clears, microtasks (Promise jobs, queueMicrotask) run before the next macrotask (setTimeout, I/O, setImmediate quirks). Therefore Promise.then callbacks usually run before setTimeout(0). Async/await is Promise sugar — await continuations are microtasks.
Full explanation
Async/await is Promise sugar — await continuations are microtasks.
Real example & use case
UI library batches DOM reads in microtasks to avoid layout thrash between timeouts.
Pros & cons
Pros: predictable ordering model. Cons: starving macrotasks with endless microtasks freezes rendering.
Code example
console.log('A');
setTimeout(() => console.log('C'), 0);
Promise.resolve().then(() => console.log('B'));
// A B CPractice code · javascript (view only · no execution)
console.log('A');
setTimeout(() => console.log('C'), 0);
Promise.resolve().then(() => console.log('B'));
// A B C