The difference between setTimeout() and setInterval()

1. Timer

Usually we use setTimeout() and setInterval() to create timers. In general, setTimeout() is used to delay the execution of a method or function, and setInterval() is generally used to refresh the form. For some forms, the fake real-time specified time refresh synchronization. setTimeout() executes after the specified number of milliseconds, and setInterval() executes every specified number of milliseconds. That is to say, setTimeout() is executed once, and setInterval() can be executed cyclically.

Many people have a common misunderstanding of Javascript's timers, thinking that they are threads. In fact, Javascript runs in a single-threaded environment . The timer just schedules the code to execute at a certain time in the future, the timing of execution is not guaranteed. No code in Javascript is executed immediately, but as soon as the process becomes idle.

Adding code to a queue does not mean that it will be executed immediately, only that it will be executed as soon as possible. For example, setting a timer to execute after 150ms does not mean that the code will be executed immediately after 150ms, it means that the code will be added to the queue after 150ms. If there is nothing else in the queue at this point, then this code will be executed, seemingly as if the code was executed at the precisely specified point in time. In other cases, the code may obviously wait for a longer event to execute.

So, the most important thing to remember about timers is that the specified interval indicates when the timer's code is added to the queue, not when the code is actually executed .

二、setTimeout()

Let's look at an example:

var btn = document.getElementById ('mybtn');
btn.onclick = function(){
    setTimeout(function(){
        // perform some action
    },250);
//other code
};
 
 

Here an event handler is set for a button. The event handler sets a timer that is called after 250ms. After the button is clicked, the onclick event handler is first queued. The timer is set after the program is executed, and after another 250ms, the specified code is added to the queue for execution.

If the onclick event handler executes for 300ms, the code for the timer will not be executed until at least 300ms after the timer is set. All code in the queue waits until the Javascript process is idle before executing, regardless of how they were added to the queue .

So let's take a look at this code:

console.log('one');
setTimeout(function(){
  console.log('two');
},0);
console.log('three');	
What is the execution result? The answer should be one three two

3. setInterval()

Timers created with setInterval() ensure that the timer code is regularly inserted into the queue. The problem with this approach is that the timer code may not finish executing before the code is added to the queue again, resulting in the timer code running several times in a row without any pauses in between.

There are two problems with using setInterval() to create a timer:

(1) Some intervals will be skipped

(2) The interval between code executions of multiple timers may be smaller than expected

Suppose, an onclick event handler uses setInterval() to set a repeating timer with a 200ms interval. If the event handler takes a little more than 300ms for the event to complete, and the timer code takes about the same amount of time, it will happen at the same time that the interval is skipped and the timer code continues to execute

To avoid these two drawbacks of setInterval(), you can use chained setTimeout() calls

setTimeout(function () {
   // Processing
    setTimeout(arguments.callee,interval);
},interval);

This pattern chained calls to setTimeout(), creating a new timer each time the function was executed. The second setTimeout() call uses arguments.callee to get a reference to the currently executing function and set another timer for it. The advantage of this is that no new timer code will be inserted into the queue until the previous timer code has finished executing, ensuring that there will not be any missing intervals. Moreover, it is guaranteed to wait at least the specified interval before the next timer code execution, avoiding continuous operation.

References:

    Advanced Programming with Javascript by Nicholas C.Zakas

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324551533&siteId=291194637