为什么我不能将函数调用(而不是函数引用或匿名函数)传递给setTimeout()? [英] Why can I not pass a function call (rather than a function reference or an anonymous function) to setTimeout()?
问题描述
请忽略这样一个事实:这段代码什么都没有,并为可能是一个无聊的问题道歉!
Please ignore the fact that this code achieves nothing and apologies for what's probably an inane question!
我知道我无法将函数调用传递给 setTimeout()
作为第一个参数,但为什么我不能这样做?
I understand that I cannot pass a function call into setTimeout()
as the first argument, but why can I not do that?
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()
来发送名称
以及它,但为什么我必须采取这些额外的步骤?
I can solve the problem by instead using a reference to printer
and using bind()
to send name
along with it, but why must I take these extra steps?
let names = ['Andy', 'Ross', 'David'];
function printer (name) {
console.log(name);
}
names.forEach(name => setTimeout(printer.bind(null, name), 1000));
结果:
Andy
Ross
David
推荐答案
这是因为执行的顺序。如果你将函数调用传递给setTimeout,函数将会马上执行,我e。该函数立即放在javascript的执行堆栈上。
This is because of the order of execution. If you pass a function call to setTimeout, the function will be executed immediately, i.e. the function is put on javascript's execution stack immediately.
如果传递函数名称,即对函数的引用,则只有在计时器结束后,该函数才会被放入javascript线程的执行堆栈中。
If you pass a function name, i.e. a reference to a function, the function is only put in the javascript thread's execution stack once the timer finishes.
这篇关于为什么我不能将函数调用(而不是函数引用或匿名函数)传递给setTimeout()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!