简体   繁体   English

为什么我需要在setTimeout中使用匿名函数才能使此代码生效?

[英]Why do I need to have anonymous function in the setTimeout for this code to work?

I'm reading a tutorial for Nodejs, but I can't understand this snippet of code, please explain it to me. 我正在阅读Nodejs的教程,但我无法理解这段代码,请向我解释一下。

function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 1 sec later');
  setTimeout(function() { callback(arg * 2); }, 1000);
}
function final() { console.log('Done', results); }

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function launcher() {
  while(running < limit && items.length > 0) {
    var item = items.shift();
    async(item, function(result) {
      results.push(result);
      running--;
      if(items.length > 0) {
        launcher();
      } else if(running == 0) {
        final();
      }
    });
    running++;
  }
}

launcher();

This code produces run 2x then pause for a second then run 2x again until there is no item in the items array. 此代码生成run 2x然后暂停一秒,然后再次运行2x,直到items数组中没有项目。

But when I removed the anonymous function in the setTimeout: 但是当我在setTimeout中删除了匿名函数时:

setTimeout(callback(arg*2), 1000);

Then the code runs with out stopping any second. 然后代码运行而不停止任何秒。 Why? 为什么?

Then the code runs with out stopping any second. 然后代码运行而不停止任何秒。 Why? 为什么?

Because instead of passing a function to setTimeout , you are passing the return value of a function call to it. 因为不是将函数传递给setTimeout ,而是将函数调用的返回值传递给它。

The function call executes immediately, and then setTimeout does nothing with the return value because it (presumably) isn't a string or a function. 函数调用立即执行,然后setTimeout对返回值不执行任何操作,因为它(可能)不是字符串或函数。

Don't remove the anonymous function wrapper. 不要删除匿名函数包装器。

The reason the anonymous delegate is needed is because setTimeout expects an object of type function as it's first argument. 需要匿名委托的原因是因为setTimeout期望一个类型为function的对象作为它的第一个参数。

So you can either give it just a pre-defined function name directly: 所以你可以直接给它一个预定义的函数名:

function foo()
{
//do something
}

setTimeout(foo, 1000);

Or a delegate: 或代表:

setTimeout(function(){/*dosomething*/}, 1000);

But this: 但是这个:

setTimeout(foo(param), 1000);

Is invalid because foo(param) isn't semantically correct in this context. 无效,因为foo(param)在此上下文中在语义上不正确。

The alternative is to do something like: 另一种方法是做类似的事情:

setTimeout("foo(param);", 1000);

Because setTimeout will also accept a string of a function, but this is a bad idea because you lose the current scope and it's a pain to debug. 因为setTimeout也会接受一个函数的字符串,但这是一个坏主意,因为你丢失了当前的范围,调试很麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我必须使用匿名 function 而不是将附加参数传递给“setTimeout”? - Why do I have to use an anonymous function instead of passing an additional argument to `setTimeout`? 为什么在此代码中需要setTimeout - Why do I need setTimeout in this code 为什么setTimeout在我的代码中不起作用? 我需要可行的代码) - why setTimeout dont work in my code? I need workable code) 为什么我需要包装器函数以setTimeout递归调用 - Why do I need a wrapper function to recursively call with setTimeout 为什么我需要将匿名函数传递给onClick事件? - Why do I need to pass an anonymous function into the onClick event? 为什么settimeout()匿名函数未在javascript中调用该函数? - why settimeout() anonymous function not call the function in javascript? 为什么我得到 setTimeout(...) is not a function? - Why do I get setTimeout(...) is not a function? 为什么我在这里得到“setTimeout 不是函数”? - Why do I get “setTimeout is not a function” here? Javascript:如果已经使用外部函数,为什么需要定义自调用匿名函数? - Javascript: Why do I need to define self invoking anonymous function if I'm already using an external function? 为什么需要匿名函数来使用setTimeout保留“this” - Why is an anonymous function required to preserve “this” using setTimeout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM