InterviewHubPRO
Section Overview
Q395

Question 395 of 521

Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

76%
JavaScript Internals (521 Qs)•Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

What is microtask

A microtask is a type of JavaScript callback that is scheduled to run immediately after the currently executing script and before the next event loop tick. Microtasks are executed after the current task completes and before any new tasks (macrotasks) are run. This ensures a fast and predictable update cycle.

Common sources of microtasks stored in the microtask queue include:

  1. Promises: When a Promise is resolved or rejected, its .then(), .catch(), and .finally() callbacks are placed in the microtask queue.
javascript
    Promise.resolve().then(() => {
     console.log('Microtask from a Promise');
    });
  1. queueMicrotask():

    A method that explicitly schedules a function to be run in the microtask queue.

javascript
      queueMicrotask(() => {
         console.log('Microtask from  queueMicrotask');
       });
  1. MutationObserver callbacks:

    Observers changes in the DOM and triggers a callback as a microtask.

javascript
        const observer = new MutationObserver(() => {
          console.log('Microtask from MutationObserver');
        })
        observer.observe(document.body, {childList: true});
  1. await:
    Await internally uses Promises, so the code after await is scheduled as a microtask.
javascript
      async function asyncFunction() {
        await null;
        console.log('Microtask from Await'); // Schedule this code as microtask
      }

Note: All of these microtasks are processed in the same turn of the event loop.