setTimeout 中的函数不起作用

function in setTimeout doesn't work

有两个函数 hello1() 和 hello2()。

function hello1(){
    console.log('hello1');
}

function hello2(){
    console.log('hello2');
}

setTimeout(hello1, 3000);
setTimeout(hello2(), 3000);

setTimeout(hello1, 3000);中,延迟3秒后打印"hello1"。

但是在setTimeout(hello2(), 3000);中,它立即打印"hello2"。

我认为是因为它必须在setTimeout中使用函数名。

如果我想像hello(1)一样延迟3秒后执行带参数的函数怎么办?

因为我想将参数传递给函数,所以我不能像 setTimeout(hello1, 3000);

那样只在 setTimeout 中使用函数名

当你在setTimeout中的函数中使用括号时,它会立即执行。

要使用带参数的函数,您可以使用任意函数作为超时函数并在其中调用您的函数。

setTimeout(function() {
    hello(1, 'param');
}, 3000);