How to Add a Task to Microtask Queue with queueMicrotask
What is queueMicrotask
queueMicrotask() is a built-in JavaScript function that adds a task to the microtask queue.
Microtasks execute immediately after the current call stack completes and before the next macrotask (e.g., setTimeout, setInterval, event handler).
Syntax
queueMicrotask(() => {
// Your code
});
Usage Example
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
queueMicrotask(() => {
console.log("Microtask Hack Frontend");
});
console.log("End");
What Will Output?
Start
End
Microtask Hack Frontend
Timeout
queueMicrotask always executes before setTimeout, even if the timer delay is 0.
Where queueMicrotask is Used
- Inside libraries and frameworks for queue optimization (React, Vue, Zone.js)
- For state updates after current call but before render
- For predictable execution order
Tip:
Use queueMicrotask if you want to execute a task asynchronously but immediately after the current operation — faster than setTimeout(...).
Conclusion
queueMicrotask()is a way to add a task to microtasks that will execute after the current stack but before macrotasks.- It's a fast and reliable way to defer code execution without waiting for the next render or event.
- Used for precise control of execution order in asynchronous operations.