JavaScript: Detailed usage of setInterval()

1 Basic grammar

setInterval() is a built-in function in JavaScript, which is used to repeatedly execute a piece of code at a specified interval to realize periodic operation. The syntax of this function is as follows:

setInterval(function, milliseconds, param1, param2, ...)

2 Parameter description

  • function: required, the function or block of code to be executed repeatedly.
  • milliseconds: required, the time interval in milliseconds between repeated executions.
  • param1, param2, ...: Optional, parameter passed to the function to be executed. Omit this parameter if no parameters need to be passed.

Notice:

If the first argument to the setInterval() function is a function, then that function will be called after each interval until the timer is canceled.

If the first parameter of the setInterval() function is a string, the string will be interpreted as a piece of JavaScript code to be executed. This usage has been deprecated and is not recommended.

If the time interval of the setInterval() function is set to 0 or a negative number, then the function will execute the function or code indicated by the first parameter immediately, and will not be executed periodically.

If the time interval of the setInterval() function is set to a small value, the timer may be inaccurate due to browser performance limitations. It is recommended to set the time interval to 100 milliseconds or more to keep the timer accurate.

3 Example of use

Use an anonymous function as the first parameter to output the current time, and the interval is 1000 milliseconds or 1 second.

// 每秒钟输出一次当前时间
setInterval(function() {
    
    
  console.log(new Date().toLocaleTimeString());
}, 1000);

4 Stop the setInterval() method

The setInterval() method will return a timer ID, which can be used to cancel the execution of the timer, as follows:

intervalId = setInterval(function() {
    
    
  console.log(new Date().toLocaleTimeString());
}, 1000);

clearInterval(intervalId );

Among them, intervalId is a variable used to save the timer object ID returned by the setInterval() method. After calling the clearInterval() method, the execution of the timer can be canceled.

Example: After printing 5 times, cancel the execution of the timer.

<!DOCTYPE html>
<html lang="en">

<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>Document</title>
</head>

<body>
    <script>
        var counter = 0;
        maxNum = 5;
        function myFunc() {
      
      
            var date = new Date();
            console.log(date.toLocaleTimeString());
            counter++;
            if (counter == maxNum) {
      
      
                clearInterval(intervalId);
                console.log('已打印' + maxNum + "次");
            }
        }

        var intervalId = setInterval(myFunc, 1000);
    </script>
</body>

</html>

Print result:

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/131009965