What is the Microtask Queue?
In JavaScript, the event loop manages the execution of code by handling two types of queues: the macro task queue (for tasks likesetTimeout and setInterval) and the microtask queue. The microtask queue is a special queue used for tasks that need to be executed as soon as the current JavaScript stack is cleared.
Tasks in the microtask queue have higher priority than tasks in the macro task queue. Common examples include:
- Promises Handler
.then,.catch,.finally - queueMicrotask API
MutationObservercallbacks
Priority Among These Microtasks:
While all three—queueMicrotask, Promise .then handlers, and MutationObserver callbacks—belong to the microtask queue, the order in which they are executed is influenced by how they are enqueued. queueMicrotask and Promise .then handlers typically execute before MutationObserver callbacks, as per their relative scheduling behavior. However, all microtasks are processed sequentially in the order they are added to the queue, meaning exact timing and context can affect the execution order.
Note :We will learn Macrotask Queue later in details, so don't worry.
How Does the Microtask Queue Work?
When the JavaScript engine processes code, it executes tasks in the following order:
- Execute the current JavaScript stack.
- Check the microtask queue. If there are tasks, execute them one by one until the queue is empty.
- Proceed to the macro task queue and pick the next task (like a
setTimeoutcallback).
This means microtasks are always executed before moving on to any macro task, ensuring their priority.
Code ExampleHere's a simple code snippet to demonstrate the microtask queue:
console.log('Script start');
setTimeout(() => {
console.log('Macro task: setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Microtask: Promise.then');
});
queueMicrotask(() => {
console.log('Microtask: queueMicrotask');
});
console.log('Script end');
// Output:
// Script start
// Script end
// Microtask: Promise.then
// Microtask: queueMicrotask
// Macro task: setTimeoutNotice how the microtasks are executed before the setTimeout callback despite being queued later.
Key Takeaways
- Microtasks are always prioritized over macrotasks in the event loop.
- Use microtasks for operations that need to run immediately after the current execution.
- Excessive microtasks can block macro tasks, causing performance issues.
Best Practices
While microtasks are powerful, they should be used judiciously. Here are some tips:
- Avoid flooding the microtask queue with too many tasks.
- Understand the priority differences to write more efficient code.
- Leverage
queueMicrotaskfor lightweight immediate actions.