[英]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.