front-end-interview-handbook/packages/quiz/questions/what-are-microtasks-and-mac.../en-US.mdx

132 lines
4.1 KiB
Plaintext

---
title: What are microtasks and macrotasks?
---
## TL;DR
In JavaScript, tasks are managed by the event loop and are categorized into:
1. **Macrotasks**:
- Higher-level events like script execution, user interactions, timers, etc.
- Added to the macrotask queue and executed one by one.
2. **Microtasks**:
- Lower-level tasks like promise handlers, mutation observers, etc.
- These have higher priority and are executed immediately after the current script but before any macrotask.
### Event Loop Steps:
- Execute the current macrotask.
- Process all microtasks.
- Render updates (in a browser).
- Pick the next macrotask and repeat.
```js
console.log('start'); // script
setTimeout(() => console.log('setTimeout'), 0); // macrotask
Promise.resolve().then(() => console.log('Promise')); // microtask
console.log('end'); // script
// output
// start
// end
// Promise
// setTimeout
```
---
## Macrotask and microtask in JavaScript
In JavaScript, microtasks and macrotasks are two types of tasks that are managed by the event loop, which is responsible for executing code, handling events, and managing asynchronous operations
### Macrotasks
Macrotasks, also known as tasks, include operations that are queued in the event loop's `task queue`. These tasks are generally more substantial and can include:
- setTimeout(callback, delay)
- setInterval(callback, delay)
- setImmediate(callback) (Node.js only)
- I/O operations (e.g., file system operations in Node.js, network requests)
- UI rendering and other browser-specific tasks
When the event loop processes the macrotask queue, it picks and executes the tasks one by one. After a macrotask completes, the event loop checks the microtask queue first and processes any microtasks before moving on to the next macrotask. So macrotasks have lower priority than microtasks.
```js
console.log('Script start');
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
console.log('Script end');
// Output:
// Script start
// Script end
// setTimeout callback
```
### Microtasks
Microtasks are smaller tasks that are usually executed immediately after the currently executing script and before any macrotask is executed. Microtasks typically include:
- Promises (e.g., Promise.then and Promise.catch callbacks)
- `MutationObserver` callbacks
- `queueMicrotask` (callback)
Microtasks are generally intended for short, quick tasks that need to be executed soon after the current operation completes. They have a higher priority than macrotasks, meaning they are executed before the event loop moves on to the next macrotask.
```js
console.log('Script start');
Promise.resolve()
.then(() => console.log('Promise microtask'))
.catch((err) => console.error(err));
console.log('Script end');
// Output:
// Script start
// Script end
// Promise microtask
```
### Event Loop Process
The event loop follows this order of execution:
- Execute the current macrotask.
- Execute all microtasks in the microtask queue.
- Render any updates (if applicable).
- Move on to the next macrotask.
This process repeats until there are no more tasks to execute
```js
console.log('Script start');
setTimeout(() => console.log('setTimeout'), 0);
queueMicrotask(() => console.log('queueMicrotask microtask'));
console.log('Script end');
// Output:
// Script start
// Script end
// queueMicrotask microtask
// setTimeout
```
The key difference is that microtasks have a higher priority than macrotasks and are executed immediately after the current macrotask, before rendering or moving on to the next macrotask. This allows for more precise and responsive handling of asynchronous operations, such as promises
## Further reading
- [The event loop - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop)
- [Tasks, microtasks, queues and schedules](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/)
- [Unraveling Macrotasks and Microtasks in JavaScript: What Every Web Developer Should Know](https://dev.to/bymarsel/unraveling-macrotasks-and-microtasks-in-javascript-what-every-developer-should-know-53mc)
- [https://javascript.info/event-loop](https://javascript.info/event-loop)