[ITEM 5] QUESTION: What is queueMicrotask?
The asynchronous model of JavaScript relies on the concept of the event loop and task queues. The queueMicrotask function is a platform-built mechanism that allows you to explicitly add a new microtask to the JavaScript engine's special microtask queue.
When you call queueMicrotask(() => {}), the passed anonymous function does not execute immediately. It enters the microtask queue and is guaranteed to execute right after the execution of the current synchronous code block completes, but before control is handed over to other types of tasks or UI rendering.
The main feature of microtasks is their highest priority within the event loop. For example, macrotask queues, such as setTimeout or setInterval, have significantly lower priority. The engine will always empty the entire microtask queue to the end first, and only then proceed to execute the next macrotask.
The queueMicrotask function conceptually works in the exact same way as creating and resolving a promise via a construct like Promise.resolve().then(() => {}). However, using queueMicrotask is a cleaner, more native, and readable way to schedule microtasks when you do not need to create the promise object itself just to execute deferred code.
This tool is often used by libraries and frameworks for batch processing of state updates, deferred resource cleanup, or guaranteeing that certain code will execute asynchronously, but as early as possible, without the delays characteristic of timers.