Home >Web Front-end >JS Tutorial >In-depth understanding of JavaScript execution mechanism
The content this article brings to you is about in-depth understanding of JavaScript execution mechanism. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First of all, what we all know is that JavaScript is a single-threaded language, so we can conclude:
JavaScript is executed in the order of statementsFirst look:
let a = '1' console.log(a) let b = '2' console.log(b)
Obviously everyone knows the result, output 1, 2 in sequence
However, another way:
setTimeout(function() { console.log(1) }) new Promise(function(resolve) { console.log(2) for(var i = 0;i< 10;i++){ i === 10 && resolve() } }).then(function() { console.log(3) }) console.log(4)
At this time, look at the sequential execution of the code, output 1, 2, 3, 4. Okay, put it in the browser and run it, what? The output is actually 2, 4, 3, 1. What about executing them in order as promised? Next, we need to understand the execution mechanism of JavaScript.
First of all, JavaScript is a single-threaded language. In the latest Web-worker launched in HTML5, the core of JavaScript being a single-threaded language has not changed. Therefore, JavaScript multi-threading is simulated based on single thread. So keep in mind that JavaScript is a single-threaded language.
Tasks are divided into two categories:
Synchronous tasks
Asynchronous tasks
When we open the page, the rendering of the page is a lot of synchronous tasks, and the time-consuming tasks of loading images and audio resources are asynchronous tasks. The main content of the time loop is:
When a task enters the execution stack, it is judged whether it is a synchronous task or an asynchronous task. If it is a synchronous task, it enters the main thread for execution and asynchronously enters the Event Table. Register function.
When the specified event is completed, the Event Table will move this function into the event queue
After the task in the main thread is completed, go The task queue reads the corresponding function and enters the main thread to execute
The above process is repeated continuously, which constitutes an event loop
where js The engine has a monitoring process that constantly checks whether the main thread execution stack is empty. Once it is empty, it will go to the time queue to check whether there are functions waiting to be called.
For example:
setTimeout( function() { console.log(1) }, 0) console.log(2)
First setTimeout enters the Event Table
Execute console.log(2)
The function executed by setTimeout enters the event queue
The main thread reads the function execution from the event queue
This is The reason why the function will not be executed immediately even if setTimeout(fn, 0)
is set. However, even if the main thread is empty, 0ms cannot be reached. According to the HTML standard, the minimum is 4ms.
There is also a function similar to setTimeout
. For setInterval
, it is executed in a loop. Regarding the execution sequence, setInterval
will place the registered function into the Event Queue at specified intervals. If the previous task takes too long, you also need to wait.
But one thing to note is that for setInterval(fn, ms)
, it is not executed once every ms
, but every ms
There will be fn
entering the task queue. That is to say, if the execution event of the callback function of setInterval
exceeds the delay ms
, then the event interval will not be visible.
In addition to generalized synchronous tasks and asynchronous tasks, there are also more detailed divisions of tasks, divided into:
macro-task (macro task): including the overall code script, setTimeout, setInterval
micro-task (micro task): Promise, process.nextTick
The order of the event loop determines the execution order of the js code. After entering the overall code (macro task), the first cycle starts. Then execute all microtasks. Then start from the macro task again, find one of the task queues to be executed, and then execute all micro tasks.
Use a piece of code to illustrate:
setTimeout(function() { console.log('1'); }) new Promise(function(resolve) { console.log('2'); resolve() }).then(function() { console.log('3'); }) console.log('4');
This code is used as a macro task to start the first cycle
First When setTimeout
is encountered, its callback function enters the macro task event queue
When Promise
,Promise## is encountered #Execute immediately, output 2,
thenThe task enters the microtask event queue
then, output 3
console.log('1'); setTimeout(function() { console.log('2'); process.nextTick(function() { console.log('3'); }) new Promise(function(resolve) { console.log('4'); resolve(); }).then(function() { console.log('5') }) }) process.nextTick(function() { console.log('6'); }) new Promise(function(resolve) { console.log('7'); resolve(); }).then(function() { console.log('8') }) setTimeout(function() { console.log('9'); process.nextTick(function() { console.log('10'); }) new Promise(function(resolve) { console.log('11'); resolve(); }).then(function() { console.log('12') }) })I don’t know what your answer is? Next, let’s analyze it: First round:
console. log()Output 1
setTimeout() Enters the macro task queue
Process.nextTick()Enter microtask queue
Then encounter Promise
, execute immediately, output 7, then
is added to the microtask queue
Encounter the second setTimeout
, enter the macro task queue
Then execute two micro tasks
ExecutionProcess.nextTick()
Output 6
Execute then
, output 8
This is the first The cycle is completely over, and the second round of event loop is carried out, that is, the first setTimeout
first encounters console.log()
, output 2
encountered Process.nextTick()
, enter the microtask queue
encounteredPromise
Immediately execute output 4, then
Enter the microtask queue
Then execute the first microtask, output 3
Execute then and output 5
so that the second round of event loop ends, and finally execute the second setTimeout
, the second setTimeout
The principle is similar to the above, so I won’t repeat the explanation. So the final result is: 1,7,6,8,2,4,3,5,9,11,10,12
Related recommendations:
Detailed explanation of js execution mechanism examples
Event Loop of JavaScript running mechanism
The above is the detailed content of In-depth understanding of JavaScript execution mechanism. For more information, please follow other related articles on the PHP Chinese website!