I published an article about setTimeout and setInterval about half a year ago, but now I go back and read it carefully and find that there are many shortcomings and errors. In fact, setTimeout and setInterval are not as simple as they are literally understood. To truly master and understand these two methods, we must start with the javascript single-threaded mechanism.
[Open the Door] How does setTimeout and setInterval work?
We know that js is executed in a single thread. In fact, the so-called "Asynchronous call" of setTimeout and setInterval is actually implemented by inserting the code segment into the code execution queue.
How to calculate the insertion time point? Naturally, we need to use what we call timer, that is, timer. When setTimeout and setInterval are executed, timer will find the code insertion point accurately according to the time you set. When the queue is "normally" executed to the insertion point, timer callback is triggered, that is, the callback function we set:
Copy codeThe Code is as follows:
Function fn (){
/*
Here is some codes
*/
SetTimeout (function () {alert ('OK! ')}, 1000 );
}
The above example is our common usage and should be easy to understand. But can timer be so accurate? Can code queue execution be so normal?
[Cutting Root] re-recognize the so-called "Asynchronous"
As we know, in fact, setTimeout and setInterval are simply implementing code delayed execution (or asynchronous execution) by inserting code into the code queue ). But in fact, the so-called Asynchronization is just an illusion-it also runs on a thread!
Then the problem arises. What if the code execution time before the Code insertion point exceeds the set time for passing in setTimeout or setInterval? Let's take a look at this Code:
Copy codeThe Code is as follows:
Function fn (){
SetTimeout (function () {alert ('Can you see me? ');}, 1000 );
While (true ){}
}
What do you think is the execution result of this code? The answer is that alert will never appear.
Why? Because the while code is not fully executed, the code inserted after it will never be executed.
To sum up, JavaScript is actually a single-threaded product. No matter how asynchronous, it is impossible to break through the single thread obstacle. Therefore, many "Asynchronous calls" (including Ajax) are actually just "pseudo-asynchronous. As long as you understand this concept, it may be difficult to understand setTimeout and setInterval.