The event loop mechanism consists of three parts:
- Call Stack
- Microtask Queue
- Message Queue
Event-loop will be executed globally line by line at the beginning. When a function is called, the task will be pushed to the call stack. The pressed function is called Frame, and when the function returns, it will be popped from the call stack
Synchronous code execution
Take a look at the following code execution:
When func2() is executed, console.log(2) is executed and pops up after execution.
Func1 () now enters the call stack:
When func1() is entered,console.log(1) is pushed onto the call stack, executed, popped,
To the console. The log (3) by the
Final result:
Asynchronous code: add setTimeout
After adding setTimeout in the above code
(Shortening the process of func1)
After setTimeout(fetch,setInterval) is executed, the code is pushed into the message queue and called after the synchronous code of the call stack is completed
So the end result:
Asynchronous code: Add promises
When a Promise(async await) is added, the asynchronous code in the Promise will be pushed into the microqueue, and after the synchronous code is completed, the code in the microqueue will be pushed into the call stack in order.
The code in the message queue must wait until the code in the microqueue is empty before it can continue executing.
Final result:
To summarize the code execution priority of the event loop:
Sync code >Promise(async await)>setTimeout(fetch,setInterval)