Good programmer web front-end sharing JS engine execution mechanism, please first focus on two points in mind! JS is a single-threaded language.
JS EventLoop is the JS execution mechanism. An in-depth understanding of JS execution is equivalent to an in-depth understanding of eventloop in JS.
Q: Why is JS single threaded? Why asynchrony? How does a single thread achieve asynchrony?
The emergence of technology is closely related to real-world application scenarios. Again, let’s answer these three questions with a realistic scenario.
(1) Why is JS single threaded?
JS was originally designed to be used in browsers, so imagine if JS in browsers were multithreaded.
Scenario Description:
So now we have two processes, process1process2, and since it’s a multi-process JS, they’re working on the same DOM at the same time. Process1 deleted the DOM, and Process2 edited the DOM, issuing two contradictory commands at the same time. How should the browser execute?
It’s easy to understand why JS is designed to be single-threaded.
(2) Why is JS asynchronous?
Scenario Description:
If asynchrony is not present in JS, it can only be executed from top to bottom, and if the previous line takes too long to parse, the following code will be blocked. For users, blocking means “stuck”, which leads to a poor user experience.
So, asynchronous execution exists in JS.
(3) how to achieve asynchronous JS single thread?
Since JS is single-threaded, can only be executed on a thread, how to achieve asynchronous?
Is through the eventloop (eventloop), understand the eventloop mechanism, understand the JS execution mechanism.
Eventloop (1)
Example 1, observe the order in which it is executed
console.log(1)setTimeout(function(){console.log(2)},0)console.log(3)
The result is: 132
In other words, the function in setTimeout is not executed immediately, but is executed after a period of time to meet certain conditions. This kind of code is called asynchronous code.
So, here we first know a kind of classification in JS, is to divide the task into: synchronous task and asynchronous task.
The execution mechanism of JS is:
Check whether the JS is synchronous or asynchronous. If the JS is synchronous, it enters the main process. If the JS is asynchronous, it enters the EventTable
Asynchronous tasks register functions in the EventTable and are pushed to the EventQueue when triggering conditions are met
Synchronous tasks are executed on the main thread until the main thread is idle, and then the eventQueue is checked to see if there are any asynchronous tasks that can be executed, and if so, pushed to the main process
The eventLoop is called the eventLoop.
So in the example above, can you describe the order in which it is executed?
Console. log(1) is a synchronization task placed in the main thread
SetTimeout () is an asynchronous task that is put into the EventTable and pushed to the EventQueue after 0 seconds
Console. log(3 is the synchronization task, put in the main thread
After control bars 1 and 3 are printed, the main thread checks the EventQueue to see if there are any executable functions and executes the setTimeout function.
Eventloop (2)
So eventLoop was my understanding of the JS execution mechanism until I came across the following code.
SetTimeout (function(){console.log(‘ timer started ‘)});
NewPromise (function(resolve){console.log(‘ execute for loop now ‘);
for(vari=0; i<10000; i++){i==99&&resolve();
}}). Then (function(){console.log(‘ execute then function ‘)}); Console. log(‘ code execution ends ‘);
Try to analyze the JS execution mechanism we just learned above:
SetTimeout is an asynchronous task that is put into an EventTable
NewPromise is a synchronization task that is placed in the main process and directly prints console.log(‘ Execute for loop soon ‘).
The functions in.then are asynchronous tasks that are placed in eventTable
Console. log(‘ end of code execution ‘) is synchronized code that is placed in the main process and executed directly
So, the result is: execute the for loop immediately – the code finishes – the timer starts – execute the then function?
Instead of executing the for loop, the code ends, the then function starts, and the timer starts
So, should asynchronous tasks be executed in a specific order, not sequentially? In fact, the division between asynchronous and synchronous is not accurate.
And the exact way to divide it is:
Macro-task: includes the entire code script, setTimeout, and setInterval
Micro-task: Promise, process.nexttick
According to this classification, the JS execution mechanism is:
Execute a macro task and place microtasks in the “event queue” of microtasks if they are encountered
After the execution of the current macro task is complete, the system will view the “event queue” of the micro task and execute all the micro tasks successively
Repeat the above steps and combine eventLoop (1) eventLoop (2) to create a more accurate JS execution mechanism
Try to analyze Example 2 according to the execution mechanism just learned:
First execute the macro task under script. When setTimeout is encountered, place it in the macro task “queue”
When you see a newPromise, just execute it, print “I’m going to execute the for loop.”
When you encounter the then method, it is a microtask and you put it in the “queue” of microtasks.
Print “End of code execution”
When the macro task of this round is finished, I look at the micro task of this round, I find a function in the then method, and I print “Execute the then function”.
At this point, the eventloop for this round is complete.
In the next loop, execute a macro task and find a setTimeout function in the macro task queue that prints “Timer started”.
So the final order of execution is: execute the for loop immediately, the code finishes, execute the then function, and the timer starts
4. Talk about setTimeout
What does this setTimeout code mean? We usually say: after 3 seconds, the setTimeout function will be executed
SetTimeout (function(){console.log(‘ executed ‘)},3000)
After 3 seconds, setTimeout functions will be pushed to eventQueue, and tasks in eventQueue will only be executed if the main thread is idle.
Therefore, this function will only be executed after 3 seconds if (1)3 seconds later and (2) the main thread is idle
If the main thread does a lot of work and takes more than 3 seconds to execute, such as 10 seconds, then the function can only be executed after 10 seconds.