What are microtasks (microtasks)?
Microtasks are small tasks that run right after the current code (the current macrotask), before the next macrotask from the queue starts. They form a separate structure, the Microtask Queue.
The key idea
JavaScript has two levels of tasks:
| Type | Examples | When it runs |
|---|---|---|
| Macrotasks (Tasks) | setTimeout, setInterval, DOM events, fetch callbacks | After the stack is cleared |
| Microtasks | Promise.then, Promise.catch, queueMicrotask, MutationObserver | Right after the current task, before the next macrotask |
That is, after the current code (for example, a function) finishes, the Event Loop first checks the microtask queue. If there are tasks in it, they all run one after another until the queue is empty.
Example
javascript
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');Step by step:
console.log('1')-> runs immediately Output:1setTimeout(..., 0)-> the callback goes into the macrotask queue (task queue)Promise.then(...)-> the callback goes into the microtask queueconsole.log('4')-> runs immediately Output:4- The current stack is empty -> all microtasks run ->
console.log('3') - Only after that do macrotasks run ->
console.log('2')
Final output order:
javascript
1
4
3
2What creates microtasks
| Source | Example |
|---|---|
| Promise | Promise.resolve().then(...) |
| queueMicrotask() | queueMicrotask(() => { ... }) |
| MutationObserver | Tracking DOM changes |
Difference between microtasks and macrotasks
| Property | Microtasks | Macrotasks |
|---|---|---|
| Queue | Microtask Queue | Task Queue |
| Examples | Promise.then, queueMicrotask | setTimeout, fetch, click |
| Priority | Higher, run first | Lower |
| When they run | After the current code, but before the next event | After all microtasks |
Be careful with microtasks
If you keep adding new microtasks from inside a then handler forever, the engine will never reach the next macrotask - you get a "frozen" Event Loop:
javascript
function loop() {
Promise.resolve().then(loop);
}
loop(); // the browser will hangSummary
| Term | Description |
|---|---|
| Microtask | A small task that runs after the current code and before the next macrotask |
| Microtask Queue | Holds callbacks from Promise.then, queueMicrotask, etc. |
| Priority | Higher than macrotasks |
| Event Loop order | Stack -> all microtasks -> the next macrotask |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.