What is Microtask Queue in JavaScript: Explanation and Example
microtask queue in JavaScript is a special queue that holds tasks to run immediately after the current script finishes but before rendering or other tasks. It is mainly used for promises and other asynchronous operations to ensure they run as soon as possible in the event loop.How It Works
Imagine JavaScript as a single worker who does one job at a time. When the worker finishes a task, they check if there are any urgent small tasks waiting in a special box called the microtask queue. These microtasks get priority and run before the worker moves on to bigger tasks or updates the screen.
This queue mainly holds things like promise callbacks. When a promise resolves, its callback is put into the microtask queue to run right after the current code finishes but before the browser does other things like rendering or handling user events. This keeps the app responsive and predictable.
Example
This example shows how a microtask runs before a normal task scheduled with setTimeout. The promise callback (microtask) runs first, even though it was created after the timeout.
console.log('Start'); setTimeout(() => { console.log('Timeout callback'); }, 0); Promise.resolve().then(() => { console.log('Promise callback'); }); console.log('End');
When to Use
Use the microtask queue when you want to run code right after the current script finishes but before the browser does other work like rendering or handling events. This is common with promises, where you want to react to results as soon as possible.
Real-world uses include updating UI after data loads, chaining asynchronous operations, or running cleanup tasks immediately after a promise resolves. It helps keep your app smooth and predictable by controlling the order of asynchronous code.
Key Points
- The microtask queue runs tasks immediately after the current code finishes.
- It has higher priority than the normal task queue (like
setTimeoutcallbacks). - Promises use the microtask queue to schedule their callbacks.
- This helps JavaScript keep asynchronous code predictable and fast.