![](/img/trans.png)
[英]why settimeout() anonymous function not call the function in javascript?
[英]Why can I not pass a function call (rather than a function reference or an anonymous function) to setTimeout()?
请忽略以下事实:对于可能是一个愚蠢的问题,此代码无法实现任何事情,并道歉!
我知道我不能将函数调用作为第一个参数传递给setTimeout()
,但是为什么我不能这样做呢?
let names = ['Andy', 'Ross', 'David'];
function printer (name) {
console.log(name);
}
names.forEach(name => setTimeout(printer(name), 1000);
结果:
Andy
timers.js:327
throw new TypeError('"callback" argument must be a function');
^
我可以通过使用对printer
的引用并使用bind()
来发送name
来解决问题,但是为什么我必须采取这些额外的步骤?
let names = ['Andy', 'Ross', 'David'];
function printer (name) {
console.log(name);
}
names.forEach(name => setTimeout(printer.bind(null, name), 1000));
结果:
Andy
Ross
David
这是因为执行顺序。 如果将函数调用传递给setTimeout,则该函数将立即执行,即该函数会立即放入javascript的执行堆栈中。
如果传递函数名称(即对函数的引用),则仅在计时器结束后才将函数放入javascript线程的执行堆栈中。
您可以尝试以下方法:
setTimeout(function(){printer(name)}, 1000)
setTimeout
应该将函数作为其第一个参数。
请参考:
https://www.w3schools.com/jsref/met_win_settimeout.asp
在这里,您将函数的结果作为undefined
的第一个参数传递。
您可以这样做:
setTimeout(printer, 1000, name)
传递函数引用的正确方法是使用回调。
names.forEach(name => setTimeout(function() {
printer(name);
}, 1000));
回调包含对该函数的引用。
setTimeout(callbackFunction, milliseconds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.