What is the Microtask Queue and How Does It Work? | by Jesse Langford | Apr, 2022

Adobe Inventory Photographs

Just a few weeks in the past I had a colleague come to me for assist. They had been trying so as to add a synthetic wait time to an asynchronous perform.

The code regarded one thing like this.

The anticipated conduct is: task1 runs, then after 5 seconds task2, and at last task3.

The precise conduct they noticed was task1 runs, then task3, and at last task2. My colleague needed to know why the perform was not ready for setTimeout to complete earlier than persevering with.

The explanation task2 is working after task3 is the Microtasks queue.

The JavaScript engine has an occasion loop that waits for duties. As duties are available in, they’re executed within the order they arrive. Contained in the occasion loop, there’s a sub-queue referred to as the Microtasks queue.

The Microtask queue blocks the remainder of the occasion loop from working till all Microtasks have been accomplished. Guarantees go into the Microtasks queue. That is why functions “wait” for Guarantees to resolve earlier than shifting on to the subsequent activity.

From my colleague’s instance, there are three duties added to the occasion loop when the perform runs. Task1, setTimeout, and task3. setTimout doesn’t return a promise so it will get added to the common activity queue.

Occasion Loop Instance:

Duties     | setTimeout
Microtasks| task1, task3

Task1 goes to run first, then task3 will run because it’s subsequent up within the Microtasks queue. As soon as the Microtasks queue is empty, common duties will run.

So the setTimeout perform will full in 5 seconds. As soon as setTimeout is full task2 can be added to the occasion loop. Task2 will get added into the Micortasks queue as a result of it returns a Promise. This explains why my colleague skilled task1 then task3 then task2.

As a way to implement the supposed wait conduct, the setTimeout perform must be wrapped in a Promise. As soon as it’s in a Promise it is going to be part of task1 and task3 within the Micro duties queue.

Now, task3 can be run when the brand new Promise has been resolved.

The brand new Promise can be resolved after task2 has been accomplished and the resolve perform has been run.

More Posts