SetTimeout and setInterval

  1. Call the function after the delay time is specified
  2. To call the function periodically

Use the setInterVal:

function doStuff(){
// this is code that needs to be executed for a period of time
}
setInterVal(doStuff, 100);
Copy the code

Here’s how to use setTimeout to simulate setInterval:

function tick() {
    doStuff();
    setTimeout(tick, 100);
}
tick();
Copy the code

Take a look at the difference between the two under normal conditions:

SetInterval performs doStuff every 100ms, and setTimeout performs doStuff every 100ms. Therefore, the interval between each timer is 100 + T(doStuff execution time is T). This T is the key to this article.

  • If T can be ignored, the effect is basically the same.
  • When T <= 100, the interval for setInterval is 100 and the interval for setTimeout is 100+T.
  • If T > 100, setTimeout remains as shown above, with an interval of 100+T between two timers. What about setInterval?

Take a look at the picture below:

At 0ms, timer 1 starts to enter the macro task queue. At 100ms, timer 1 starts to execute doStuff1, the queue is empty, and timer 2 enters the queue. At 200ms, timer 3 was skipped because timer 2 was still in the queue. Browsers do not create two identical interval timers at the same time. At 300ms, timer 2 starts running, the queue is empty, and timer 4 enters the queue. And so on ~

So let’s verify that with code. T Set the parameter to 140ms. We let the timer run 5 times, according to the above understanding, the total running time should be: 100+5*140 = 800ms. The code is as follows:

      let i = 0;
      console.time("Total time");

      function doStuff() {
        console.log("delay");
        dead(140);
        console.timeEnd("Test");
      }

      function dead(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
      }

      let timer = setInterval((a)= > {
        i++;
        if (i > 4) {
          clearInterval(timer);
          setTimeout((a)= > {
            console.timeEnd("Total time");
          }, 0);
        }
        console.log("interval start");
        console.time("Test");
        doStuff();
      }, 100);
Copy the code

Running results:

It can be seen that the timer ran for 5 times, and the total time was indeed 800ms. What if the code in doStuff is asynchronous? For example, we often use the request interface. Simple local server, 140ms return result. The code is so simple that I’m not going to do it. Here is the js code:

      let i = 0;
      console.time("Total time");

      function delay() {
        fetchData();
      }

      function fetchData() {
        return fetch("/home", {
          method: "POST"
        })
          .then(res= > {
            console.log("res>>>>>>"); })}let timer = setInterval((a)= > {
        i++;
        if (i > 4) {
          clearInterval(timer);
          setTimeout((a)= > {
            console.timeEnd("Total time");
          }, 0);
        }
        delay();
      }, 100);
Copy the code

Console output:

Conclusion:

  • SetInterval simply queues code at a certain point in time, and skips if a timer is already in the queue. Browsers do not create two identical interval timers at the same time.
  • The asynchronous code in setInterval does not block the creation of a new timer.

Reference article:

  • JS Ninja Secrets chapter 13.2
  • Do you really know setTimeout and setInterVal?
  • This time, thoroughly understand the JavaScript execution mechanism
  • SetTimeout & setInterval for web timers