JavaScript 中的 setInterval() 方法用于在每个给定的时间间隔重复执行指定的函数。它在给定的间隔内评估表达式或调用函数。此方法会一直调用函数,直到窗口关闭或调用了 clearInterval() 方法。此方法返回一个数字值或非零数字,用于标识创建的定时器。

setTimeout() 方法不同,setInterval() 方法会多次调用函数。此方法可以使用或不使用 *window* 前缀编写。

setInterval() 方法的常用语法如下:

语法

window.setInterval(function, milliseconds);

参数值

此方法接受两个参数值 function*milliseconds*,如下所示。

function: 包含将要执行的代码块的函数。

milliseconds: 此参数表示每次执行之间的时间间隔长度,单位为毫秒。它定义了代码将被执行的频率。如果其值小于 10,则使用值 10。

如何停止执行?

我们可以使用 clearInterval() 方法来停止 setInterval() 方法中指定的函数的执行。setInterval() 方法返回的值可以作为 clearInterval() 方法的参数,以取消超时。

让我们通过一些示例了解如何使用 setInterval() 方法。

示例1

这是使用 setInterval() 方法的简单示例。在这里,每隔 3 秒钟,一个警报对话框会显示。我们没有使用任何方法来停止 setInterval() 方法中指定的函数的执行。因此,方法会一直执行,直到窗口关闭。

<!DOCTYPE html>
<html>
<head>
  <title>setInterval() method</title>
</head>
<body>
  <h1>Hello World :) :)</h1>
  <h3>This is an example of using the setInterval() method</h3>
  <p>Here, an alert dialog box displays on every three seconds.</p>

  <script>
    var a;

    a = setInterval(fun, 3000);

    function fun() {
      alert(" Welcome to the javaTiku.cn ");
    }
  </script>
</body>
</html>

输出

1.png

现在,我们来看另一个使用 setInterval() 方法的示例。

示例2

在这里,背景颜色将在每 200 毫秒更改一次。我们没有使用任何方法来停止 setInterval() 方法中指定的函数的执行。因此,方法会一直执行,直到窗口关闭。

<!DOCTYPE html>
<html>
<head>
  <title>setInterval() method</title>
</head>
<body>
  <h1>Hello World :) :)</h1>
  <h3>This is an example of using the setInterval() method</h3>
  <p>Here, the background color changes on every 200 milliseconds.</p>

  <script>
    var var1 = setInterval(color, 200);

    function color() {
      var var2 = document.body;
      var2.style.backgroundColor = var2.style.backgroundColor == "lightblue" ? "lightgreen" : "lightblue";
    }
  </script>
</body>
</html>

输出

2.png

背景颜色将在每 200 毫秒的间隔内从 lightgreen* 更改为 lightblue*。经过 200 毫秒后,输出将为 -

3.png

示例3

在上一个示例中,我们没有使用任何方法来停止颜色之间的切换。在这里,我们使用 clearInterval() 方法来停止上一个示例中颜色的切换。

我们必须点击指定的 *stop* 按钮以看到效果。

<!DOCTYPE html>
<html>
<head>
  <title>setInterval() method</title>
</head>
<body>
  <h1>Hello World :) :)</h1>
  <h3>This is an example of using the setInterval() method</h3>
  <p>Here, the background color changes on every 200 milliseconds.</p>
  <button onclick="stop()">Stop</button>

  <script>
    var var1 = setInterval(color, 200);

    function color() {
      var var2 = document.body;
      var2.style.backgroundColor = var2.style.backgroundColor == "lightblue" ? "lightgreen" : "lightblue";
    }

    function stop() {
      clearInterval(var1);
    }
  </script>
</body>
</html>

输出

4.png

背景颜色将在 200 毫秒的时间间隔内开始更改。单击指定的 *stop* 按钮后,颜色之间的切换将停止在相应的背景颜色上。单击按钮后的输出将为 -

5.png

标签: js, JavaScript, JavaScript语言, JavaScript开发, JavaScript语法, JavaScript脚本, JavaScript教程, JavaScript入门, JavaScript入门教程, JavaScript进阶, JavaScript宝典, JavaScript学习, JavaScript指南, JavaScript大全