Set Timeout()基础教程文档

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

JavaScript中的 setTimeout()方法用于等待指定的时间间隔后执行函数。此方法返回一个表示计时器ID值的数值。
setInterval()方法不同, setTimeout()方法将执行只能运行一次。该方法可以带有或不带有 window 前缀。
我们可以使用 clearTimeout()方法停止超时或阻止执行 setTimeout()方法中指定的功能。 setTimeout()方法返回的值可以用作 clearTimeout()方法的参数来取消计时器。
常用的 setTimeout()方法的语法如下所示。

语法

window.setTimeout(function, milliseconds);

参数值

此方法采用两个参数值 function 毫秒 > 定义如下。
function::该功能包含将要执行的代码块。
milliseconds:该参数表示执行该功能后的时间间隔。时间间隔以毫秒为单位。它的默认值为0。它定义了代码执行的频率。如果未指定,则使用值 0
让我们通过一些说明来了解 setTimeout()方法的使用。

Example1

这是使用 setTimeout()方法的简单示例。在这里,警报对话框将以两秒钟的间隔显示。我们没有使用任何方法来阻止执行 setTimeout()方法中指定的功能。因此, setTimeout()方法在给定的时间间隔后仅执行一次指定的函数。
<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Here, an alert dialog box will display after two seconds. </p>
<script>
var a;
a = setTimeout(fun, 2000);
function fun() {
alert(" Welcome to the lidihuo.com ");
}
</script>
</body>
</html>

Example2

这是另一个使用 setTimeout()方法的示例。在这里,一个新的选项卡会在两秒钟的时间间隔后打开,并在两秒钟的打开后关闭。我们正在使用 window.open()方法打开一个新标签,并使用 window.close()方法关闭该打开的标签。
因为我们没有使用任何方法来阻止执行 setTimeout()方法中指定的功能。因此,在给定的时间间隔后,该函数仅执行一次。
<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Here, a new tab will open after 2 seconds and close after 2 seconds. </p>
<script>
var a = setTimeout(fun1, 2000);
function fun1()
{
var win1 = window.open();
win1.document.write(" <h2> Welcome to the lidihuo.com </h2>");
setTimeout(function(){win1.close()}, 2000);
}
</script>
</body>
</html>
输出
 JavaScript setTimeout()方法
之后两秒钟后,将打开一个新标签,如下所示-
 JavaScript setTimeout()方法
新在两秒钟的间隔后,选项卡将关闭。

Example3

在上述示例中,我们没有使用任何方法来阻止执行< strong> setTimeout()。在这里,我们使用 clearTimeout()方法来停止函数的执行。
我们必须单击给定的 stop >在两秒钟之前按一下按钮。
<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Click the following button before 2 seconds to see the effect. </p>
<button onclick = "stop()"> Stop </button>
<script>
var a = setTimeout(fun1, 2000);
function fun1()
{
var win1 = window.open();
win1.document.write(" <h2> Welcome to the lidihuo.com </h2>");
setTimeout(function(){win1.close()}, 2000);
}
function stop() {
  clearTimeout(a);
}
</script>
</body>
</html>
输出
 JavaScript setTimeout()方法
该如果用户在两秒钟前单击 stop 按钮,则输出将保持不变。否则,新标签页将在两秒钟后打开,并在两秒钟后关闭。