在 setTimeout() 中将参数传递给匿名函数

Passing parameter to anonymous function in setTimeout()

我想弄清楚为什么以下代码不起作用

function testFunction(fn) {
    setTimeout(fn(1), 1000)
}

this.testFunction(id => console.log("id; " + id))

删除 setTimeout() 并简单地使用 fn(1) 将控制台记录所需的结果

id; 1

您的函数接受一个参数,因此它会立即被调用。将算法放在匿名函数中。

setTimeout(() => fn(1), 1000)

正如 Jaromanda X 在评论中指出的那样,任何需要传递给匿名函数的参数都必须传递给 setTimeout 函数,而不是使用括号表示法 - fn(1) - 就像那样在传递给 setTimout

之前调用匿名函数
function testFunction(fn) {
    setTimeout(fn, 1000, 1)
}