而不是函数引用或匿名函数

而不是函数引用或匿名函数

本文介绍了为什么我不能将函数调用(而不是函数引用或匿名函数)传递给 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() 连同它一起发送 name 来解决问题,但是为什么我必须采取这些额外的步骤吗?

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,该函数将立即执行,即该函数会立即放入 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:24