JS Coding Questions Logo
JS Coding Questions
#391💼 Interview💻 Code

What is microtask

Advertisement

728x90

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
1Promise.resolve().then(() => {
2  console.log('Microtask from a Promise');
3  });

2. queueMicrotask():

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

javascript
1queueMicrotask(() => {
2  console.log('Microtask from  queueMicrotask');
3  });

3. MutationObserver callbacks:

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

javascript
1const observer = new MutationObserver(() => {
2  console.log('Microtask from MutationObserver');
3  })
4  observer.observe(document.body, {childList: true});

4. await:

Await internally uses Promises, so the code after await is scheduled as a microtask.

javascript
1async function asyncFunction() {
2  await null;
3  console.log('Microtask from Await'); // Schedule this code as microtask
4  }

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

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 49

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
391of476