Skip to main content

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:

TypeExamplesWhen it runs
Macrotasks (Tasks)setTimeout, setInterval, DOM events, fetch callbacksAfter the stack is cleared
MicrotasksPromise.then, Promise.catch, queueMicrotask, MutationObserverRight 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:

  1. console.log('1') -> runs immediately Output: 1
  2. setTimeout(..., 0) -> the callback goes into the macrotask queue (task queue)
  3. Promise.then(...) -> the callback goes into the microtask queue
  4. console.log('4') -> runs immediately Output: 4
  5. The current stack is empty -> all microtasks run -> console.log('3')
  6. Only after that do macrotasks run -> console.log('2')

Final output order:

javascript
1 4 3 2

What creates microtasks

SourceExample
PromisePromise.resolve().then(...)
queueMicrotask()queueMicrotask(() => { ... })
MutationObserverTracking DOM changes

Difference between microtasks and macrotasks

PropertyMicrotasksMacrotasks
QueueMicrotask QueueTask Queue
ExamplesPromise.then, queueMicrotasksetTimeout, fetch, click
PriorityHigher, run firstLower
When they runAfter the current code, but before the next eventAfter 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 hang

Summary

TermDescription
MicrotaskA small task that runs after the current code and before the next macrotask
Microtask QueueHolds callbacks from Promise.then, queueMicrotask, etc.
PriorityHigher than macrotasks
Event Loop orderStack -> all microtasks -> the next macrotask

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.