Asynchronous macrotasks and microtasks

macro task

script (overall code)

setTimeout

setInterval

I/O

UI interaction event

postMessage

MessageChannel

setImmediate (Node.js environment)

micro task

Promise.then

Object.observe

MutationObserver

process.nextTick (Node.js environment)

-------------------------------------------------- -------------- Let's guess the order of code execution

 -------- output result

I drew a crude picture

Let me describe the execution sequence. The synchronous code must be executed first, and it enters the execution stack directly, so the first output "I am synchronous code", under each task unit, including synchronous and asynchronous, after the execution is completed, It will detect that there are no unexecuted microtasks in the current unit tasks under this scope, and if there are any, they will be executed, and if not, the next task unit will be executed. So when the synchronization code is executed, you will find a microtask, so enter "I am a microtask" for the second one, and you will have two macrotasks, because the written setTimeout time is the same, so just look at the front and back In order, the first setTimeout macro task is executed first. Under this task unit, the synchronous task code must be executed first, so it outputs "I am macro task 1", and then there is no micro task, and it is found that there are The microtask executes "I am the microtask in the first macrotask", and then registers a setTimeout macrotask after the queue, but it will not be executed first, because the second macrotask is registered before him, And the time is the same. Then it came to the second macro task, the synchronization code was executed first, and "I am macro task 2" was output , and then a setTimeout macro task was registered behind the queue, and then the macro task registered by macro task 1 was reached, and the output "I am the first macro task in the first macro task" , and then execute the macro task registered in the second macro task, and output "I am the first macro task in the second macro task".

Because the setTimeout we use here is the same time, so the output is like this, but if the setTimeout writes the time, the answer will be different.

If I write like this, the output is 2 1 

Because, the two will be placed in the worker thread, when the following setTimeout reaches 500 milliseconds, it will be put into the task queue,

When, and the setTimeout above has not reached 1000 milliseconds, it has to wait. When the function execution stack is empty, the first one in the task queue will go in and execute, and 2 will be output. The above setTimeout enters the task queue at 1000 milliseconds, and then outputs 1. So it is not to see who registers first, we found that the task queue does not put task 2 and task 3 together at once, but Which timer is up and which one to put in.

 Thanks

Guess you like

Origin blog.csdn.net/ZHUzhuzhu08/article/details/122058430