What are macro- and micro-tasks?
Answer from AI
sobes.tech AI
Macrotasks are large, high-level stages of browser operation, such as parsing HTML, building the DOM, constructing the CSSOM, calculating styles, building the rendering tree, layout, painting, and compositing. They form the main rendering pipeline.
Microtasks are smaller, more detailed actions that are executed after the current macrotask completes and before the next one begins. These include handling promises (Promise), MutationObserver, queueMicrotask.
The key difference is that microtasks are always executed immediately after the current macrotask, while the next macrotask (for example, the next rendering frame or handling a setTimeout timer event) is only executed after the microtask queue is empty.
Example execution order:
// Macrotask (initial code)
console.log('Start');
// Macrotask (timer)
setTimeout(() => {
console.log('Timer');
}, 0);
// Microtask (promise)
Promise.resolve().then(() => {
console.log('Promise');
});
// Macrotask (end of initial code)
console.log('End');
Console output:
Start
End
Promise
Timer
Execution order:
- The initial macrotask (main script) runs.
console.log('Start').setTimeoutschedules a macrotask.Promise.resolve().then()schedules a microtask.console.log('End').- The main macrotask finishes.
- Microtask queue is checked:
Promise.resolve().then()executes. console.log('Promise').- Microtask queue is empty.
- Browser processes tasks in the event loop, moving to the next macrotask.
- The
setTimeoutmacrotask executes. console.log('Timer').- The macrotask completes.
This understanding is important for managing the order of asynchronous operations and understanding how the Event Loop works.