An in depth understanding of setTimeout and setInterval

  • 2020-03-26 23:46:31
  • OfStack

About six months ago I published an article on setTimeout and setInterval, but now I look back and see that there are a lot of shortcomings and errors. In fact, setTimeout and setInterval are not as simple as we might think. To really grasp and understand both of these methods, you have to start with javascript's single-threaded mechanism.

How do setTimeout and setInterval work?
As we know, js is single-threaded. So what setTimeout and setInterval call asynchronously is actually done by inserting code snippets into the execution queue of the code.

How do you calculate the insertion time? And of course we're going to use what we call a timer, which is a timer. When setTimeout and setInterval are executed, the timer will find the insertion point of the code "exactly" according to the time you set. When the queue executes "normally" to the insertion point, the timer callback, which we set up, is triggered:
function fn() { 
setTimeout(function() {alert('ok!')},1000); 

The above example is our common usage and should be easy to understand. But is the timer really that accurate? Can the execution of the code queue really be that normal?

[extermination] rediscover the so-called "asynchronous"
As you've just learned, setTimeout and setInterval simply implement deferred (or asynchronous) execution of code by inserting code into the code queue. But the truth is that asynchrony is just an illusion -- it also runs on a thread!
So the question is, what happens if the code before the insertion point runs longer than the set time passed in setTimeout or setInterval? Let's take a look at this code:
function fn() { 
setTimeout(function(){alert('can you see me?');},1000); 
while(true) {} 

What do you think is the result of this code? The answer is, alert never appears.
Why is that? Because the while code isn't finished, the code inserted later never executes.
To sum up, in fact, JS is a single thread product. There is no way "asynchronous" can break through the single-threaded barrier. So many "asynchronous calls" (including Ajax) are really just "pseudo-asynchronous." Once you understand such a concept, it may not be difficult to understand setTimeout and setInterval.

Related articles: