JS setInterval()基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

JavaScript中的 setInterval()方法用于在每个给定的时间间隔重复指定的函数。它以给定的时间间隔评估表达式或调用函数。该方法继续调用函数,直到关闭窗口或调用 clearInterval()方法为止。此方法返回一个数字值或一个非零数字,用于标识创建的计时器。
setTimeout()方法不同, setInterval()方法多次调用该函数。此方法可以带有或不带有 window 前缀。
setInterval()方法的常用语法是在下面给出:

语法

window.setInterval(function, milliseconds);

参数值

此方法采用两个参数值 function 毫秒 > 定义如下。
function::该功能包含将要执行的代码块。
milliseconds:该参数表示每次执行之间的时间间隔的长度。时间间隔以毫秒为单位。它定义了代码执行的频率。如果它的值小于10,则使用值10。

如何停止执行?

我们可以使用 clearInterval()方法来停止执行 setInterval()方法中指定的功能。 setInterval()方法返回的值可以用作 clearInterval()方法的参数来取消超时。
让我们了解一下用法 setInterval()方法的说明。

Example1

这是使用 setInterval()方法。在此,每隔3秒显示一个警告对话框。我们没有使用任何方法来停止执行 setInterval()方法中指定的功能。因此,该方法将继续执行该功能,直到关闭窗口为止。
<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 lidihuo.com ");
}</script>
</body>
</html>
现在,还有另一个使用 setInterval()方法的示例。

Example2

此处,背景颜色每200个都会变化毫秒。我们没有使用任何方法来停止执行 setInterval()方法中指定的功能。因此,该方法将继续执行该功能,直到关闭窗口为止。
<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>
输出
 JavaScript setInterval()方法
该背景将每隔200毫秒从 lightgreen 更改为 lightblue 。 200毫秒后,输出将为-
 JavaScript setInterval()方法

Example3

在上面的示例中,我们没有使用任何方法来停止颜色之间的切换。在这里,我们使用 clearInterval()方法停止上一个示例中的颜色切换。
我们必须单击指定的 stop 按钮查看效果。
<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>
输出
 JavaScript setInterval()方法
该背景颜色将在200毫秒后开始更改。单击指定的 stop 按钮后,颜色之间的切换将停止在相应的背景颜色上。单击按钮后的输出将是-
 JavaScript setInterval()方法