The purpose of this article is to ensure that you thoroughly understand JavaScript execution mechanism, if you do not understand this article, you can hit me.
Whether you're a novice or a veteran of JavaScript, whether you're interviewing for a job or a daily development job, we often encounter situations where we need to know the output and order of the given lines of code. Because JavaScript is a single-threaded language, we can conclude that:
- JavaScript is executed in the order in which the statements appear.
See here readers to hit: I do not know that JS is a line of execution? You still talking? A little Ann, just because JS is a line of execution, so we think JS is this:
Let a = ' 1 '= ' 2 '; Console.log (b);
View Code
However, in fact, JS is this:
SetTimeout (function() { console.log (' timer started ')}); New Promise (function(resolve) { Console.log (' Execute for Loop now '); for (var i = 0; i < 10000; i++) { = = && resolve (); }}). Then (function() { console.log (' execute then function ')}); Console.log (' End of Code execution ');
According to JS is in accordance with the order of the sentence to execute this concept, I confidently write down the output:
// "Timer's starting." // "Execute the For loop now." // "execute then function." // "End of code Execution"
To Chrome on the verification, the result is completely wrong, an instant Meng, a good line to execute it?
We really have to figure out the JavaScript execution mechanism completely.
1. About JavaScript
JavaScript is a single-threaded language, and Web-worker is presented in the latest HTML5, but JavaScript is a single-threaded core that remains unchanged. So all JavaScript version of "Multithreading" is a single-threaded simulation, all JavaScript multithreading are paper Tigers
2.javascript Event Loop
Since JS is single-threaded, it is like a bank with only one window, customers need to queue up a business, the same JS task to be executed in one order. If a task takes too long, the latter task must wait. So the question comes, if we want to browse the news, but the news contains the ultra-clear picture loading is very slow, is our page stuck until the picture is fully displayed? So smart programmers divide the task into two categories:
- Synchronization Tasks
- Asynchronous task
When we open a Web site, the rendering process is a lot of synchronization tasks, such as page skeleton and page element rendering. An asynchronous task is a task that takes a lot of time, such as loading pictures and music. There is a strict text definition for this section, but the purpose of this article is to thoroughly understand the execution mechanism with minimal learning costs, so we use the guide to illustrate:
The content of the map to be expressed is expressed in words:
- The synchronous and asynchronous tasks enter different execution "places", enter the main thread synchronously, enter the event table asynchronously and register the function.
- When the specified event is complete, the event table will move the function into the event Queue.
- When the task in the main thread is completed empty, it will go to the event queue to read the corresponding function and go into the main thread execution.
- This process repeats itself, which is often called the event loop.
We can't help but ask, how do you know the main thread execution stack is empty ah? JS engine exists monitoring process, will continuously check whether the main thread execution stack is empty, once empty, will go to the event queue to check if there is a function waiting to be called.
Speaking so much text, it is better to direct a piece of code more straightforward:
var data = [];$.ajax ({ url:www.javascript.com, data:data, = = { Console.log (' send success! ') ); }}) Console.log (' End of Code execution ');
The above is a simple ajax
request code:
- Ajax enters the event Table and registers the callback function
success
.
- Execution
console.log(‘代码执行结束‘)
.
- The Ajax event completes and the callback function
success
enters the event Queue.
- The main thread reads the callback function from the event queue
success
and executes it.
Believe that through the above text and code, you have a preliminary understanding of the execution sequence of JS. Next we will study the Advanced topic: SetTimeout.
3. Love and Hate settimeout
setTimeout
There is no need to say more, everyone's first impression of him is asynchronous can be delayed execution, we often do so delay 3 seconds to execute
SetTimeout (() = { console.log (' delay 3 seconds ');},3000)
Gradually setTimeout
use more places, the problem also appeared, sometimes obviously write the delay of 3 seconds, but the actual 5, 6 seconds to perform functions, which is what?
Let's look at an example:
SetTimeout (function () {
Task ();
},3000)
Console.log (' Executive console ')
According to our conclusion, it setTimeout
is asynchronous, we should perform console.log
this synchronization task first, so our conclusion is:
// Execution Console // Task ()
To verify, the results are correct!
Then we modify the previous code:
SetTimeout (function () { task ()},+); sleep (10000000)
At first glance, actually, but we put this code in chrome, but found that the console execution task()
takes much more than 3 seconds, a good delay of three seconds, why now take so long ah?
At this point we need to re setTimeout
-understand the definition. Let's start by saying how the above code is executed:
task()
Enter the event table and register to start the timer.
- The execution
sleep
function is slow, very slow, and the timing continues.
- 3 seconds to the time, the timing of the event
timeout
completed, task()
into the event Queue, but sleep
also too slow, not finished, had to wait.
sleep
Finally executed, task()
finally from the event queue into the main thread execution.
The above process is complete, we know settimeout this function, after a specified time, the task to be performed (in this case) to task()
add to the event queue, and because it is a single-threaded task to execute one, if the previous task takes too long, then can only wait, Causes real latency to be much greater than 3 seconds.
We also often encounter setTimeout(fn,0)
such code, 0 seconds after the implementation of what is the meaning of it? Is it possible to execute it immediately?
The answer is no, setTimeout(fn,0)
the meaning is to specify a task in the main thread the earliest available idle time to execute, meaning is not to wait many seconds, as long as the main thread execution stack of all the synchronization tasks completed, the stack is empty immediately execute. To illustrate:
// Code 1console.log (' Execute here first '), setTimeout (function () { console.log (' Execute ')} ,0)// Code 2console.log (' Execute here first '); SetTimeout (function () { console.log (' execution ')},3000);
The output of code 1 is:
// do it first . // It's done.
The output of code 2 is:
// do it first . // ... 3s later// Execute
setTimeout
to add, even if the main thread is empty, 0 milliseconds is actually not up to it. According to the standard of HTML, the minimum is 4 milliseconds. Interested students can learn by themselves.
4. The setinterval of Hate and love
setTimeout
It's over, of course not to miss its twin brother setInterval
. They are the same, but the latter is the execution of the loop. For the execution order, the setInterval
registered function is placed in the event Queue every specified time, and if the previous task takes too long, the same waits.
The only thing to be aware of is that, for the time being, setInterval(fn,ms)
we already know that not every ms
second is executed fn
, but every ms
second, there is an fn
entry into the event Queue. Once setInterval
The callback function fn
execution time exceeds the delay time ms
, then it is completely invisible there is a time interval . This sentence invites the reader to taste carefully.
--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------
Transfer from Nuggets net (https://juejin.im/post/59e85eebf265da430d571f89)
Get a thorough understanding of JavaScript execution mechanisms