JavaScript教程-JavaScript 的 setTimeout() 方法

JavaScript 中的 setTimeout() 方法用于在等待指定的时间间隔后执行函数。此方法返回一个表示定时器的 ID 值的数字。
与 setInterval() 方法不同,setTimeout() 方法只执行一次函数。此方法可以使用或不使用 window 前缀编写。
我们可以使用 clearTimeout() 方法来停止超时或防止执行在 setTimeout() 方法中指定的函数。setTimeout() 方法返回的值可以作为 clearTimeout() 方法的参数,以取消定时器。
setTimeout() 方法的常用语法如下。
语法
window.setTimeout(function, milliseconds);
参数值
此方法接受两个参数值 function 和 milliseconds,如下所示。
function: 包含将要执行的代码块的函数。
milliseconds: 此参数表示执行函数之前的时间间隔。时间间隔以毫秒为单位。其默认值为 0。它定义了代码将被执行的频率。如果未指定,将使用值 0。
让我们通过一些示例了解如何使用 setTimeout() 方法。
示例1
这是使用 setTimeout() 方法的简单示例。在这里,每隔两秒钟,一个警报对话框将显示。我们没有使用任何方法来防止执行在 setTimeout() 方法中指定的函数。因此,setTimeout() 方法只在给定的时间间隔后执行指定的函数一次。
<!DOCTYPE html>
<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 javaTiku.cn ");
}
</script>
</body>
</html>
输出
示例2
这是使用 setTimeout() 方法的另一个示例。在这里,一个新的选项卡在两秒的时间间隔后打开,然后在打开两秒后关闭。我们使用 window.open() 方法来打开新选项卡,使用 window.close() 方法来关闭已打开的选项卡。
因为我们没有使用任何方法来防止执行在 setTimeout() 方法中指定的函数。因此,函数在给定的时间间隔后只执行一次。
<!DOCTYPE html>
<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 javaTiku.cn</h2>");
setTimeout(function(){win1.close()}, 2000);
}
</script>
</body>
</html>
输出
经过两秒钟后,将打开一个新的选项卡,如下所示 -
两秒后,新选项卡将关闭。
示例3
在上述示例中,我们没有使用任何方法来防止执行在 setTimeout() 方法中指定的函数。在这里,我们使用 clearTimeout() 方法来停止函数的执行。
我们必须在两秒钟之前点击给定的 stop 按钮以看到效果。
<!DOCTYPE html>
<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 javaTiku.cn</h2>");
setTimeout(function(){win1.close()}, 2000);
}
function stop() {
clearTimeout(a);
}
</script>
</body>
</html>
输出
如果用户在两秒钟之前单击 stop 按钮,输出将保持不变。否则,在两秒钟后将打开一个新的选项卡,并在打开两秒后关闭。