Preface
We know that JS is a single-threaded language, and its operating mechanism is quite special.
Below we use several examples of settimeout to show the special points of JavaScript's running mechanism
Example 1
(1); setTimeout(function(){ (2); },0); (3); // Print out 1 3 2
Example 2
('1'); setTimeout(function(){ ('2'); },0); while(1){} // Print out1,Then the browser is stuck,不会Print out2
JavaScript will first put the content that needs to be run into the task queue
However, if you encounter settimeout, you will think that this is an asynchronous task and will be placed in the asynchronous queue first
The browser will first execute the synchronous task, and then view the asynchronous queue after the synchronous task is executed.
If the execution time of the task in the asynchronous queue is up, the browser will put the task in the synchronous queue.
Right now:
Asynchronous tasks must be executed after synchronous tasks.
Example 3
for(var i = 0; i < 4; i++){ setTimeout(function() { (i); }, 1000); } // Print 4 4 4 4
Why is it printed out 4 4 4?
Because the browser will execute the for loop first
Every time a for loop is executed, a settimeout is pushed into the asynchronous queue.
After 1000 milliseconds, when the method in settimeout is executed, the value of i is already 4.
What should I do if I want to print 0 1 2 3?
Using the closure feature, cache i to a temp value
for(var i = 0; i < 4; i++){ (function(temp){ setTimeout(function() { (temp); }, 1000); })(i); } // Print 0 1 2 3
Doing this is equivalent to creating a new anonymous function every time for loop, and the value of i is stored in the memory of this anonymous function.
Students who understand the closure will definitely understand this.
Example 4
We know ES6 introduces new keyword let
Here, let has a new feature
for(let i = 0; i < 4; i ++){ setTimeout(function(){ (i); }, 1000); } // Print 0 1 2 3
Example 4 and Example 3 are only different from var and let, but the print results are completely different.
This is because let is a block-level scope
Let's define i, which is a brand new i for each for loop execution (using a different memory address)
So when printing, you can get 0 1 2 3
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.