JavaScript is a single-threaded, non-blocking programming language designed to handle asynchronous tasks efficiently. To achieve this, it uses an event loop, which consists of two main queues: the task queue (or macro task queue) and the microtask queue. Understanding the microtask queue is crucial for writing performant and predictable asynchronous JavaScript code.
The microtask queue is a special queue in JavaScript that holds microtasks, which are short-lived, high-priority tasks. Examples of microtasks include:
.then
, .catch
, .finally
).MutationObserver
API.queueMicrotask
.The microtask queue is processed immediately after the currently executing JavaScript code completes and before any tasks from the task queue are executed. This ensures that microtasks are executed as soon as possible, making them highly predictable.
Here’s how the event loop processes tasks:
This ensures that microtasks always get priority over tasks in the macro task queue.
Let’s dive into some examples to understand the microtask queue better.
console.log("Script start");
setTimeout(() => console.log("setTimeout"), 0);
Promise.resolve()
.then(() => console.log("Promise 1"))
.then(() => console.log("Promise 2"));
console.log("Script end");
Output:
Script start
Script end
Promise 1
Promise 2
setTimeout
Explanation:
console.log("Script start")
and console.log("Script end")
execute synchronously..then
) are added to the microtask queue.setTimeout
is added to the task queue.Promise 1
and Promise 2
.setTimeout
.queueMicrotask
console.log("Start");
queueMicrotask(() => console.log("Microtask 1"));
setTimeout(() => console.log("Timeout"), 0);
queueMicrotask(() => console.log("Microtask 2"));
console.log("End");
Output:
Start
End
Microtask 1
Microtask 2
Timeout
Explanation:
console.log("Start")
and console.log("End")
execute synchronously.queueMicrotask
adds callbacks to the microtask queue.Microtask 1
and Microtask 2
before the setTimeout
callback.
setTimeout(()=>console.log("Timeout"),0)
Promise.resolve()
.then(() => {
console.log("Promise 1");
return Promise.resolve();
})
.then(() => console.log("Promise 2"));
console.log("End of Script");
Output:
End of Script
Promise 1
Promise 2
Timeout
Explanation:
.then
adds its callback to the microtask queue.console.log("End of Script")
executes synchronously.Promise 1
logs, and another microtask is created for Promise 2
.Promise 2
.queueMicrotask
are key players in the microtask queue.Understanding the microtask queue gives you more control over asynchronous operations and ensures your code behaves as expected. By leveraging promises, queueMicrotask
, and other microtask APIs, you can write clean, efficient, and non-blocking JavaScript applications.
Happy coding!