JavaScript question detail
What is microtask
A microtask is a type of JavaScript callback that is scheduled to run immediately after the currently executing script and before the next event loop tick. Microtasks are executed after the current task completes and before any new tasks (macrotasks) are run. This ensures a fast and predictable update cycle.
Common sources of microtasks stored in the microtask queue include:
- Promises:
When a Promise is resolved or rejected, its
.then(),.catch(), and.finally()callbacks are placed in the microtask queue.
Promise.resolve().then(() => {
console.log('Microtask from a Promise');
});
- queueMicrotask():
A method that explicitly schedules a function to be run in the microtask queue.
queueMicrotask(() => {
console.log('Microtask from queueMicrotask');
});
- MutationObserver callbacks:
Observers changes in the DOM and triggers a callback as a microtask.
const observer = new MutationObserver(() => {
console.log('Microtask from MutationObserver');
})
observer.observe(document.body, {childList: true});
- await:
Await internally uses Promises, so the code after
awaitis scheduled as a microtask.
async function asyncFunction() {
await null;
console.log('Microtask from Await'); // Schedule this code as microtask
}
Note: All of these microtasks are processed in the same turn of the event loop.