This article shares with you relevant knowledge points about the JavaScript event loop mechanism. Friends who are interested can learn and refer to it.
As we all know, JavaScript is a single-threaded language. Although Web-Worker was proposed in html5, this has not changed the core of JavaScript being single-threaded. See this passage in the HTML specification:
To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.
To coordinate events, user interaction, scripting, UI rendering, and network processing, user engines must use event loops. Event Loop consists of two types: one based on Browsing Context and one based on Worker, both of which run independently. The following article uses an example to focus on the event loop mechanism based on Browsing Context.
Let’s take a look at the following JavaScript code:
console.log('script start'); setTimeout(function() { console.log('setTimeout'); }, 0); Promise.resolve().then(function() { console.log('promise1'); }).then(function() { console.log('promise2'); }); console.log('script end');
First guess the output sequence of this code, then enter it in the browser console to see if the actual output sequence matches yours. Is the guessed order consistent? If so, it means that you still have a certain understanding of the JavaScript event loop mechanism. Keep reading to consolidate your knowledge; and if the actual output order is inconsistent with your guess, Then the following part of this article will answer your questions.
Task Queue
All tasks can be divided into synchronous tasks and asynchronous tasks. Synchronous tasks, as the name suggests, are tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution; and Asynchronous tasks are tasks that are executed asynchronously, such as ajax network requests, setTimeout timing functions, etc., which are all asynchronous tasks. Asynchronous tasks are coordinated through the task queue (Event Queue) mechanism. The following figure can be used to roughly explain the specific situation:
# Synchronous and asynchronous tasks enter different execution environments respectively. The synchronous tasks enter the main thread, that is, the main execution stack, and the asynchronous tasks enter the main thread, that is, the main execution stack. Enter the Event Queue. If the tasks in the main thread are empty after execution, the corresponding tasks will be read from the Event Queue and pushed to the main thread for execution. The continuous repetition of the above process is what we call Event Loop.
In the event loop, each loop operation is called a tick. By reading the specification, we can know that the task processing model of each tick is relatively complex, and its key steps can be summarized as follows:
Select the oldest task that enters the queue first in this tick. If there is one, execute it (once)
Check whether Microtasks exist, if they exist Then continue to execute until the Microtask Queue is cleared
Update render
The main thread repeats the above steps
You can use a picture to illustrate the process:
I believe someone will want to ask, what are microtasks? The specification stipulates that tasks are divided into two categories, namely Macro Task (macro task) and Micro Task (micro task), and after each macro task is completed, all micro tasks must be cleared. The Macro Task here is also what we often call task. Some articles do not distinguish between them. The tasks mentioned in the following articles are all regarded as macro tasks.
(macro)task mainly includes: script (overall code), setTimeout, setInterval, I/O, UI interactive events, setImmediate (Node.js environment)
microtask mainly includes: Promise, MutaionObserver, process.nextTick (Node.js environment)
setTimeout/Promise and other APIs are task sources, and what enters the task queue is the specific execution task specified by them. Tasks from different task sources will enter different task queues. Among them, setTimeout and setInterval have the same origin.
Analysis of sample code
There are thousands of words, so it is better to explain it clearly with examples. Below we can follow the specifications and analyze the above example step by step. First, post the example code (to save you from scrolling up).
console.log('script start'); setTimeout(function() { console.log('setTimeout'); }, 0); Promise.resolve().then(function() { console.log('promise1'); }).then(function() { console.log('promise2'); }); console.log('script end');
The overall script enters the main thread as the first macro task, encounters console.log, and outputs script start
Encounters setTimeout, and its callback function is distributed to When
encounters a Promise in the macro task Event Queue, its then function is assigned to the micro task Event Queue and is recorded as then1. Then it encounters the then function again and assigns it to the micro task Event Queue. In the task Event Queue, it is recorded as then2
When it encounters console.log, it outputs script end
Micro task | |
---|---|
then1 | |
then2 |