gpt4 book ai didi

javascript - 为什么我需要在 setTimeout 中使用匿名函数才能使此代码正常工作?

转载 作者:行者123 更新时间:2023-11-30 13:15:21 25 4
gpt4 key购买 nike

我正在阅读 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();

此代码生成运行 2x,然后暂停一秒钟,然后再次运行 2x,直到 items 数组中没有项目为止。

但是当我删除 setTimeout 中的匿名函数时:

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

然后代码会不停地运行。为什么?

最佳答案

Then the code runs with out stopping any second. Why?

因为您不是将函数传递给 setTimeout,而是将函数调用的返回值传递给它。

函数调用立即执行,然后 setTimeout 不对返回值做任何事情,因为它(可能)不是字符串或函数。

不要删除匿名函数包装器。

关于javascript - 为什么我需要在 setTimeout 中使用匿名函数才能使此代码正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12192444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com