Different types of tasks enter the corresponding macro task Event Queue and micro task Event Queue.
The order of the event loop determines the execution order of the JS code. After entering the overall code (macro task), the first loop begins. Then perform all the microtasks. Then start from the macro task again, find one of the task queues to complete, and then execute all the microtasks.
The process.nexttick (node.js environment) method can fire the callback function —- at the end of the current “execution stack” —- before the next Event Loop (the main thread reads the “task queue”). That is, the task it specifies always takes place before all asynchronous tasks.
-
When the execution stack is empty, we can think of the execution stack as a stack structure that stores function calls, following the principle of first in, last out. The micro queue is empty, and the Macro queue has one and only one script.
-
The global context (script tag) is pushed onto the execution stack to synchronize code execution. During execution, the task is determined to be synchronous or asynchronous, and new macro-tasks and micro-tasks can be generated by calling some interfaces, which are pushed into their respective task queues. The script will be removed from the macro queue after the synchronized code is executed. This process is essentially the execution and dequeuing of the macro task in the queue.
-
In the previous step, we assigned a macro-task. In this step, we dealt with a micro-task. But it’s important to note that when Macro-Task is out, tasks are executed one by one; Micro-tasks, on the other hand, are executed in teams. Therefore, we process the micro queue by executing the tasks in the queue one by one and de-queuing them until the queue is empty.
If user actions and browser rendering are involved, refer to the following article.
Reference links: jishuin.proginn.com/p/763bfbd4c…
provenance