setTimeout()
方法在指定的延迟后执行一段代码。该方法只执行一次代码。
JavaScript setTimeout
的常用语法是
setTimeout(function, milliseconds);
其参数为
- function - 包含一段代码的函数
- milliseconds - 函数执行后的延迟时间
示例 1:将参数传递给 setTimeout
// program to pass parameter to a setTimeout() function
function greet() {
console.log('Hello world');
}
// passing parameter
setTimeout(greet, 3000);
console.log('This message is shown first');
输出
This message is shown first Hello world
在上面的程序中,greet()
函数被传递给 setTimeout()
。
然后,greet()
函数将在 **3000** 毫秒(**3** 秒)后调用。
因此,程序将在 **3** 秒后只显示一次文本 Hello world。
示例 2:将参数传递给函数
// program to pass parameter to function in setTimeout()
function greet(x, y) {
console.log(x);
console.log(y);
}
// passing parameter
setTimeout(greet, 3000, 'hello', 'world');
console.log('This message is shown first');
输出
This message is shown first hello world
在上面的程序中,greet()
函数需要额外的参数 x 和 y。
在调用 setTimeout()
函数时,会传递额外的参数 'hello'
和 'world'
,这些参数将被 greet()
函数使用。
另请阅读