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
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.
task2 is working after
task3 is 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.
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.
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
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
task3 within the Micro duties queue.
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.