🟢 EasyAsync JS📖 Theory Question

What is queueMicrotask() and when should you use it?

💡

Hint

Schedule a function in the microtask queue — runs after current sync, before next macrotask

Full Answer

queueMicrotask(fn) adds a callback directly to the microtask queue — the same queue that Promise callbacks use.

// Functionally equivalent:
Promise.resolve().then(() => console.log('A'));
queueMicrotask(() => console.log('B'));
// A, B — FIFO within the microtask queue

console.log('sync');
queueMicrotask(() => console.log('microtask'));
setTimeout(() => console.log('macrotask'), 0);
console.log('sync end');
// Order: sync → sync end → microtask → macrotask

Advantages over Promise.resolve().then():

  • No Promise overhead — slightly more performant
  • More explicit — clearly states "schedule as microtask"
  • Doesn't create a Promise chain
// Real use case: batch state updates
let pending = false;
function scheduleRender() {
  if (pending) return;
  pending = true;
  queueMicrotask(() => {
    pending = false;
    renderDOM(); // runs once after all sync mutations
  });
}
💡 Use queueMicrotask when you want something to run "ASAP but async" — after current sync code finishes, before any I/O or timers fire.

More Async JS Questions

🟢 EasyExplain Promises — states, chaining, and error handling.→🟢 EasyHow does async/await work under the hood?→🟢 EasyWhat is callback hell and how do you avoid it?→🟢 EasyWhat are Promise combinators and when do you use each?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint