About six months ago published an article about settimeout and setinterval, but now go back to see the fact that there are many deficiencies and errors. In fact, settimeout and setinterval are not as simple as we literally understand. To really grasp and understand these two methods, you have to start with the single-threaded mechanism of JavaScript.
How does "settimeout" and setinterval work?
We know that JS is a single-threaded execution. So actually settimeout and setinterval called "asynchronous calls" are actually implemented by inserting code snippets into the execution queue of the code.
And how do you calculate the insertion point in time? Nature is to use what we call the timer, the timer. When executing settimeout and setinterval, the timer will "accurately" locate the insertion point of the code according to the time you set. When the queue executes "normally" to the insertion point, it triggers the timer callback, which is the callback function we set:
Copy Code code as follows:
function fn () {
/*
This is some codes
*/
settimeout (function () {alert (' ok! ')},1000);
}
The above example is our usual usage and should be easy to understand. But can a timer really be that accurate? is the execution of the code queue really that normal?
"Extermination" to recognize the so-called "asynchronous"
As we've just known, in fact settimeout and setinterval just simply insert code into the Code queue to implement the code's deferred execution (or asynchronous execution). But in fact the so-called asynchronous is just an illusion-it also runs on a thread!
So the question is, what if the code execution time before the code insertion point exceeds the set time of the incoming settimeout or setinterval? Let's take a look at this piece of code:
Copy Code code as follows:
function fn () {
settimeout (function () {alert (' Can you ' I/I/I? ');},1000);
while (true) {}
}
What do you think is the result of this code? The answer is that alert will never appear.
What is this for? Because while this code is not finished, the code that is inserted in the back is never executed.
To sum up, in fact, JS is a single thread product. In any case, "asynchronous" is impossible to break through the single thread barrier. So many of the "asynchronous calls" (including Ajax) are actually just "pseudo asynchrony". As long as you understand such a concept, perhaps understanding settimeout and setinterval is not difficult.