[英]Passing parameter to anonymous function in setTimeout()
I am trying to figure out why the following code does not work 我试图弄清楚为什么以下代码不起作用
function testFunction(fn) {
setTimeout(fn(1), 1000)
}
this.testFunction(id => console.log("id; " + id))
Removing setTimeout()
and simply using fn(1)
will console log the desired result 删除setTimeout()
并仅使用fn(1)
将控制台记录所需的结果
id; ID; 1 1
Your function accepts an argument and as a consequence it is immediately invoked. 您的函数接受一个参数,因此它会立即被调用。 Put the algorithm in an anonymous function. 将算法放在匿名函数中。
setTimeout(() => fn(1), 1000)
As Jaromanda X points out in the comments, any parameters that need to be passed to the anonymous function must be passed to the setTimeout
function rather than using brackets notation - fn(1)
- as that invokes the anonymous function before it is passed to setTimout
正如Jaromanda X在注释中指出的那样,任何需要传递给匿名函数的参数都必须传递给setTimeout
函数,而不是使用方括号表示法setTimout
fn(1)
-因为它将在将匿名函数传递给setTimout
之前调用它
function testFunction(fn) {
setTimeout(fn, 1000, 1)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.