setTimeout()
方法在指定时间后执行代码块。该方法只执行一次代码。
JavaScript setTimeout 常用的语法是:
setTimeout(function, milliseconds);
它的参数是:
function-包含代码块的函数
毫秒-函数执行的时间
示例 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()
函数。