JavaScript

setInterval(), clearInterval(), setTimeout(), and clearTimeout() JS counter methods

setInterval(), clearInterval(), setTimeout(), and clearTimeout() JS counter methods, someone asked me to explain?
 window.setInterval()

Introduction

Call a function (function) periodically or execute a piece of code.

 var intervalID = window.setInterval(func, delay[ param1, param2, ...]);
 var intervalID = window.setInterval(code, delay);

Here,

  • intervalIDIs the only identifier for this repetitive operation and can be passed as a parameter clearInterval().
  • func Is the function you want to call repeatedly.
  • codeIs another grammar application, refers to the code that consists of a string of characters that you want to repeat (it is not recommended to use this syntax , the reason for not recommending is the same as eval() ).
  • delayIs the number of milliseconds per delay (one second equals 1000 milliseconds), and each invocation of the function occurs after that delay. As with setTimeout , the actual delay time may be slightly longer.

It should be noted that IE does not support the ability to pass extra parameters to the delay function in the first syntax. If you want to achieve the same functionality in IE, you must use a compatible code (see the section callback arguments ).

Example

Example 1: Basic usage

  var intervalID = window.setInterval(animate, 500);

Example 2: Switching between two colors

In the following example, the function will be called flashtext()once every second until you clear the unique identifier for this iteration by pressing the Stop button.intervalID。

<!DOCTYPE html>
<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title>setInterval/clearInterval example</title>
    <script type="text/javascript">
        var nIntervId;
 
        function changeColor() {
            nIntervId = setInterval(flashText, 500);
        }
 
        function flashText() {
            var oElem = document.getElementById("my_box");
            oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
        }
 
        function stopTextColor() {
            clearInterval(nIntervId);
        }
    </script>
</head>

<body onload="changeColor();">
    <div id="my_box">
        <p>Hello World</p>
    </div>
    <button onclick="stopTextColor();">Stop</button>
</body>
</html>

 

window.clearInterval()

Overview

Cancel the repeated execution of the settings.setInterval

CODE

window.clearInterval(intervalID)

intervalIDIs the ID of the repetitive action you want to cancel. This ID is an integer and is used by setInterval()

window.setTimeout

Overview

Call a function or execute a code snippet after the specified delay time.

CODE

 var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
 var timeoutID = window.setTimeout(code, delay);

Description:

  • timeoutIDIs the numeric ID of the delay operation, which can then be used as a parameter to the window.clearTimeout method.
  • funcIs delaythe function you want to execute after milliseconds.
  • codeIn the second syntax, delaythe code you want to execute after milliseconds (using this syntax is not recommended, the reason for not recommending is the same as eval() )
  • delay Is the number of milliseconds delayed (one second equals 1000 milliseconds), the function call will occur after the delay. But the actual delay time may be slightly longer, see the note below.

It should be noted that IE does not support the ability to pass extra parameters to the delay function in the first syntax. If you want to achieve the same functionality in IE, you must use a compatible code (see the section c allback arguments ).

Remarks

You can use window.clearTimeout() to cancel the delayed operation.

If you want your code to be called repeatedly (such as every N milliseconds), consider using it window.setInterval().

Pass string literals

  setTimeout()

    window.setTimeout(function() {
        alert("Hello World!");
    }, 500);
    window.setTimeout("alert('Hello World!');", 500);

Strings are interpreted and executed in the global setTimeout()scope , so variables in the string are not available when the function is executed.

The setTimeout() method executes the function after waiting for the specified time, and only executes the passed handle function once. The setInterval() method executes the passed handle function once every specified interval, looping until the window is closed or clearInterval() .

<!Doctype html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setInterval</title>
</head>
<body>
    <p><input type="button" value="setTimeout" /> <input type="button" value="clearTimeout" /></p>
    <p>Click the button to see the effect (pops every 2s): <input type="button" value="setInterval" /> <input type="button" value="clearInterval" /></p>
    <div id="ul1">
        <input type="text" id="clock" size="35" />
        <button onclick="window.clearInterval(c)">stop Interval</button>
    </div>
    <script type="text/javascript">
        var c = self.setInterval("clock()", 50);
        function clock() {
            var t = new Date();
            document.getElementById("clock").value = t;
        }
        var timeout = function () {
            alert('Popate after waiting for 2s, only this time! clearTimeout can stop execution during waiting time!')
        }
        var interval = function () {
            alert('Eject every 2s loop until clearInterval or close the window!')
        }
        var input = document.getElementsByTagName('input');
        console.log(input.length);
        var clearTimeoutFun = null;
        var clearIntervalFun = null;
 
        input[0].onclick = function () {
            clearTimeoutFun = setTimeout(timeout, 2000);
        }
        input[1].onclick = function () {
            clearTimeout(clearTimeoutFun);
        }
        input[2].onclick = function () {
            clearIntervalFun = setInterval(interval, 2000);
        }
        input[3].onclick = function () {
            clearInterval(clearIntervalFun);
        }
    </script>
</body>
</html>

 

 

Post your comments / questions