Detailed explanation of the usage and difference between JavaScript setTimeout and setInterval

Table of contents

I. Overview

II. setTimeout() function

III. setInterval() function

IV. New Year Countdown Case


Javascript's setTimeOut and setInterval functions are widely used. They are used to handle delays and scheduled tasks. The following article mainly introduces the usage and differences of JavaScript setTimeout and setInterval. You can refer to it if you need it.

I. Overview

First of all, the setTimeout() and setInterval() functions are two very important "time functions" in JavaScript . Therefore, when we learn JavaScript, we must have an in-depth study of these two functions. This function is also frequently used!

 Among them, if these two functions are summarized in one sentence , it should be like this:

setTimeout(): This function can delay the execution of events according to the set time value.

setInterval(): This function can periodically execute the time according to the set time value as the interval.

Of course, this is just a brief introduction, we will explain it to you in detail in the following section.

II. setTimeout() function

The first is our setTimeout() function . What is its format:

setTimeout(function,times, param1, param2, …);

setTimeout is a timer function that allows us to execute a function after a specified time. Among them, function is the function we want to execute, times is the delay time (in milliseconds), and param1 , param2, ... , etc. are the parameters passed to the function (optional). For example, let's look at this simple code:

setTimeout(function(){

    alert("hello,setTimeout()");

}, 1000);

After running, it will pop up a pop-up box after a delay of 1s, where the unit of 1000 is milliseconds!

After learning this, everyone thinks it is very simple, right? Okay, let me give you a piece of code and let you guess what it will output :

for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        alert(i)
    }, 1000)
}

Hey, someone wants to say, simple, isn't this the output: 1 2 3 4 5?

However, in reality, it outputs 6 6 6 6 6, so why is this? Because setTimeout() is an asynchronous execution function , in human terms, the function body inside it will not run immediately every time it is executed, but will be thrown into the execution queue and wait for the "mainline tasks" to be completed. will execute it .

So after 5 for loops, the value of i is 5, passed in, and 6 6s popped out.

So is there any solution? I will give you two solutions:

1️⃣Use  keyword let:

for (let i = 1; i <= 5; i++) {
   setTimeout(function () { 
       alert(i);
   }, 1000)
}

Results of the:

So why is it OK to just use let:

In fact, after using let, the execution mechanism has not changed , it is still the last executed alert() , but let can pass the updated variable i into the function body every time , that is, after each time i is incremented by 1, the new variable i will be added. The value is put into the corresponding function in the queue , thus solving this problem.

2️⃣Define  an external variable:

We define a variable externally, so that this variable will be put into the queue every time without changing its execution mechanism:

var j = 1;
for (i = 1; i <= 5; i++) {
    setTimeout(function () {
        alert(j)
        j++;
    }, 1000);
}

The second method is easier to be understood by others and is more suitable for actual use when working on projects.

Note : setTimeout returns a unique identifier, we can use the clearTimeout function to cancel this timer. code show as below:

// 延迟 1 秒后输出 "Hello, world!"
const timerId = setTimeout(() => {
  console.log("Hello, world!");
}, 1000);
// 取消定时器
clearTimeout(timerId);

This code defines a setTimeout timer, which will execute a function after 1 second and output the string "Hello, world!". At the same time, it stores the returned timer ID in the variable timerId. The next line of code calls the clearTimeout function and passes the timerId. This function will cancel the previously set timer, thereby avoiding the execution of the function. Therefore, this code ends up outputting nothing.

III. setInterval() function

setInterval() is also a timer function in JavaScript, used to set periodic scheduled tasks. Compared with the setTimeout function, it is less complicated, but its function is indeed very powerful. Let’s take a look at its usage syntax first. :

setInterval(function,times,param1, param2, …);

The format is the same as setTimeout(), where the function parameter represents the function to be executed, the delay parameter represents the time interval of the timer (in milliseconds), and param1, param2, ... represent the parameters passed to the function (optional). The setInterval() function can loop and repeat the function at the set times interval . Let's test it with a small example:

setInterval(function(){
    alert('hello,setInterval()');
}, 1000);

After running, every 1 second, a pop-up window will pop up, displaying this paragraph.

After running it, of course we will have a question, that is, can it stop executing in a loop at a specific time ? The answer is yes, but we need to define an object of the setInterval() function . We usually name it: timer :

var i = 5;
var timer = setInterval(function(){  
    i --;   
    if(i < 0){   
       clearInterval(timer);
    }    
    alert(i);     
 }, 1000);

In the above code, we created an object called timer for setInterval , and externally we defined another variable i . After that, every time we execute the function in Interval, we let i-1  , reduce it to below 0, and clear the timer. :

clearInterval(timer object);

The above sentence is the code to clear the timer , just pass in an object of the setInterval() function .

✔ Summary: The difference between setInterval() and setTimeout()

setInterval() and setTimeout() are both timer functions in JavaScript, but they have the following differences:

1. setInterval() repeats the specified task after delaying the specified time until canceled or the page is closed. And setTimeout() executes the specified task after delaying the specified time and only executes it once;

2. The execution interval of setInterval() is fixed, while setTimeout() can dynamically adjust the delay time;

3. There may be a cumulative error in setInterval() because its execution time is calculated relative to the end of the last task. If the executed task takes longer than the specified time interval, a cumulative error will occur. Each execution of setTimeout() is calculated relative to the start time of the last task, and there is no cumulative error;

4. setInterval() may have an impact on performance because it will repeatedly execute the specified task and occupy CPU resources. And setTimeout() will only execute the task once after the specified time, which has less impact on performance.

Therefore, in general, if we need to execute a specified task periodically, we can use setInterval(); if we only need to execute a task once after a specified time, we can use setTimeout().

✔ Precautions

Pay attention to the following points when using setInterval():

1. The minimum value of the delay parameter is 4 milliseconds. If the set value is less than 4 milliseconds, it will be forced to 4 milliseconds.

2. setInterval() returns a timer ID, and you can use the clearInterval() function to cancel the timer.

3. Since JavaScript is single-threaded, if the function execution time is too long, the response performance of the page may be affected. Therefore, it is recommended to minimize the execution time when writing functions.

IV. New Year Countdown Case

Finally, let’s use the learned setTimeout() function and setInterval() function to make a New Year countdown case :

We want something like this:

First, display a 60-second countdown on the screen;

After the countdown reaches 0, a pop-up window displays Happy New Year!

Someone read this description and thought that our code should look like this:

var element = document.getElementById("xin-nian")
var clock = 60;
var timer = null;
timer = setInterval(function () {
  element.innerHTML = "新年倒计时:" + clock + " !";
  console.log(clock)
  clock--;
  if (clock < 0) {
    clearInterval(timer);
    alert("新年快乐!");
  }
}, 1000);

At first glance, it seems that there is no problem, but when it is actually run, due to a small delay in writing content to the html, a pop-up window will appear before the final countdown number 0 is written . Therefore, we need to add a pop-up window at the last second of the countdown. , use setTimeout() to make a small buffer :

if (clock < 0) {
   clearInterval(timer);
   setTimeout(function () {
      alert("新年快乐!") 
   }, 500)};

So the complete code should be like this:

<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>新年倒计时</title>
  <style>
    body {
      background-image: url(./1.jpg);
    }
  </style>
</head>

<body>
  <h1 id="xin-nian" style="text-align: center;margin-top: 250px;font-size: 50px;"></h1>
  <script>
    var element = document.getElementById("xin-nian")
    var clock = 60; var timer = null; timer = setInterval(function () {
      element.innerHTML = "新年倒计时:" + clock + " !";
      console.log(clock)
      clock--;
      if (clock < 0) {
        clearInterval(timer);
        setTimeout(function () {
          alert("新年快乐!")
        }, 500)
      }
    }, 1000)
  </script>
</body>

</html>

The effect achieved is as follows:

References

Usage of setInterval() and setTimeout()  |  Detailed explanation of timer setTimeout and setInterval

Usage of timers setTimeout() and setInterval() in JS  |  JS setInterval() and setTimeout() timers

Detailed explanation of the example of the effect of setInterval and setTimeout on the page  |  A brief discussion on the understanding of "do not use setInterval, use setTimeout"

Guess you like

Origin blog.csdn.net/sunyctf/article/details/135176815