JavaScript 如何在运行时更改setinterval()方法的时间间隔

JavaScript 如何在运行时更改setinterval()方法的时间间隔

在本文中,我们将学习如何在运行一个元素后更改setInterval()的时间间隔。setInterval()方法会读取一次时间,并以固定间隔调用该函数。下面讨论了解决此问题的两种方法:

  • 使用clearInterval()方法
  • 使用setTimeout()方法

方法1:使用clearInterval()方法

setInterval()方法会返回一个数字ID。可以将该ID传递给clearInterval()方法来清除/停止setInterval计时器。在这种技术中,在每个setInterval()后连续触发clearInterval(),以停止上一个setInterval()并初始化具有新计数器的setInterval()。

语法:

clearTimeout(name_of_setTimeout)

示例: 此示例展示了上述解释方法的应用。

<!DOCTYPE html>
<html>
<head>
    <title>
        How to Change the Time Interval of
        setinterval() Method after Running
        one Element using JavaScript ?
    </title>
</head>
 
<body>
    <div id="message"></div>
 
    <script>
        // Output message
        let msg = document.getElementById("message");
 
        let t = 200; // Timer
 
        // Stores the setInterval ID used by
        // clearInterval to stop the timer
        var interval;
 
        f1();
 
        // Function that changes the timer
        function changeTimer() {
            t = t * 1.2;
        }
 
        // Function that run at irregular intervals
        function f1() {
 
            // Clears the previous setInterval timer
            clearInterval(interval);
            msg.innerHTML +=
                "<br>Function Fired</br>"
             
            changeTimer();
            interval = setInterval(f1, t);
        }
    </script>
</body>
</html>

输出:

JavaScript 如何在运行时更改setinterval()方法的时间间隔

方法2:使用setTimeout() 方法

这种技术比之前的方法更简单。 setTimeout() 方法在一段时间后触发一个函数。定时器是我们希望在其后运行函数的时间。在这种技术中,执行所需的任务后,我们更改计时器的值并再次调用 setTimeout()。由于计时器的值发生变化,每次函数调用都在不同的间隔内被调用。

语法:

window.setTimeout(function, milliseconds);

示例: 该示例展示了上述解释的方法的使用。

<!DOCTYPE html>
<html>
<head>
    <title>
        How to Change the Time Interval of
        setinterval() Method after Running
        one Element using JavaScript ?
    </title>
</head>
 
<body>
    <div id="message"></div>
 
    <script>
        // Output message
        var msg = document.getElementById("message");
 
        var t = 200; // Timer
 
        // Stores the setInterval ID used by
        // clearInterval to stop the timer
        var interval;
 
        f1();
 
        // Function that changes the timer
        function changeTimer() {
            t = t * 1.2;
        }
 
        // Function that run at irregular intervals
        function f1() {
 
            // Clears the previous setInterval timer
            clearInterval(interval);
            msg.innerHTML +=
                "<br>Function Fired</br>"
 
            changeTimer();
            interval = setInterval(f1, t);
        }
    </script>
</body>
</html>

输出:

JavaScript 如何在运行时更改setinterval()方法的时间间隔

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程