运行此代码(在 Node.js 中)时,“Count”对于“count”较大的值运行为负值。 谁是罪魁祸首,“伯爵”还是“链条”? 编写“洪水”函数的正确方法是什么,以便它在 setTimeout() 之后安排下一次调用。
flood = function( count) {
chain = function() {
--count;
console.log("Count " + count)
if( count > 0 ) {
setTimeout(chain, 1);
}
};
chain();
}
runit = function (count,par) {
console.log("RUNIT: " + count + " , " + par )
for( var i = 0 ; i < par ; i ++ ) {
flood(count)
}
}
runit(3,4)
谢谢
更新: 如果我调用 chain() 而不是 setTimeout(chain,1),计数永远不会变为负值。
最佳答案
chain
是全局的,因为您没有使用 var 关键字。这使得您的代码的行为类似于 runit(3, 4)
。
4次:
flood(2); // Prints "Count 2" and calls setTimeout
然后发生第一轮异步回调。在该轮链中,当它引用正确的函数时,您将进行另一轮使用正确的链并打印“Count 1”四次,但在这一轮中,当您调用 setTimout
时,您会从最近的洪水调用中传递链,因此现在您有 4 个单链的异步调用,您将得到:
"Count 0"
"Count -1"
"Count -2"
"Count -3"
使用 var
声明它,您的问题将得到解决:
var chain = function() { ...
关于javascript - 如何捕获私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706121/