Event loop
- Synchronous and asynchronous tasks go to different execution “places”, synchronous tasks go to the main thread, asynchronous tasks go to the Event Table and register functions.
- When the specified Event completes, the Event Table moves this function to the Event Queue.
- If the tasks in the main thread are empty after execution, the Event Queue will read the corresponding function and enter the main thread for execution.
- This process is repeated over and over again, known as an Event Loop.
In addition to the generalized synchronous and asynchronous tasks, we have a more detailed definition of tasks:
- Macro-task: Includes overall code script, setTimeout, setInterval, setImmediate, I/O, UI rendering
- Micro-task: Promise, process.nextTick (nodejs), MutationObserver
Different types of tasks will enter the corresponding Event Queue, for example, **setTimeout** and **setInterval** will enter the same Event Queue
Macro task Event Queue Micro task Event Queue
setTimeout nextTick then
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.
setTimeout(function() {
console.log('setTimeout');
})
new Promise(function(resolve) {
console.log('promise');
}).then(function() {
console.log('then');
})
console.log('console');
Copy the code
-
This code enters the main thread as a macro task.
-
When a setTimeout is encountered, its callback function is registered and distributed to the macro task Event Queue. (The registration process is the same as above and will not be described below)
-
A Promise is then encountered, the New Promise is immediately executed, and the then function is dispatched to the microtask Event Queue.
-
If console.log() is encountered, execute immediately.
-
Ok, the whole script is executed as the first macro task. What are the microtasks? We found that then is executed in the microtask Event Queue.
-
Ok, the first round of the Event loop is over, so let’s start the second round, starting, of course, with the macro task Event Queue. We find the callback function corresponding to setTimeout in the macro task Event Queue and execute it immediately.
-
The end.
Javascript is a single-threaded language
Event Loop is the execution mechanism of javascript
Reference article source: juejin.cn/post/684490…