JavaScript · Event Loop · Junior · Comparison
What is the difference between microtasks and macrotasks?
Short Interview Answer
Macrotasks include timers, I/O, UI events; microtasks include promise reactions and `queueMicrotask`. Microtasks run before the next macrotask and after the current call stack clears.
Detailed Explanation
After a script/task finishes, the engine processes all pending microtasks before rendering or the next timer task. That is why `Promise.resolve().then(...)` runs before `setTimeout(fn, 0)`. Continuous microtask scheduling can starve rendering and timers. Node also has `process.nextTick` (runs before promise microtasks in Node's model). Knowing the ordering is essential for predicting output questions and avoiding UI jank.
Example
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
// sync, promise, timeoutInterview Tip
Memorize one canonical ordering example and explain why.
Common Mistake
Treating `setTimeout(0)` as 'faster than promises'.