gpt4 book ai didi

javascript - JS 停止控制流直到异步 setTimeout 返回

转载 作者:行者123 更新时间:2023-11-30 16:44:33 25 4
gpt4 key购买 nike

我正在尝试使用同步计数器和递归自调用函数来阻止控制流到我的代码的其余部分,直到设置的超时异步函数调用终止并递增我的同步计数器。然而事实证明,出于某种原因,setTimeout 函数甚至从未被调用过,无论是在递归函数内部还是外部。递归调用是否以某种方式优先于 setTimeout 函数?

var localSynchCounter = 0;
(function asynchCall1(){
//only runs the very first iteration of this function
console.log("running..: "+localSynchCounter);
if (localSynchCounter == 0) {
console.log("running autonymous first time");
localSynchCounter ++;

setTimeout(function() {
localSynchCounter ++;
console.log("set time out1 ocmpleted");
}, 0);

setTimeout(function() {
localSynchCounter ++;
console.log("set time out2 ocmpleted");
}, 0);
}

else if (localSynchCounter == 3){
console.log("functions have returned");
return;
}
asynchCall1();

})();

最佳答案

Does the recursive call somehow take priority over the setTimeout functions?

是的,因为它是同步的(尽管名为 asynchCall1),而超时是异步的。

However it turns out that for some reason the setTimeout functions are never even called whether inside the recursive function or even outside of it.

如果您的脚本会终止,它们会(它们已被“安排”执行)。目前您的递归是无限的,因为 localSynchCounter 递增一次但永远不会到达调用结束的 3

要使其正常工作,您需要异步调用 asynchCall(从超时开始):

var localCounter = 0;
(function asyncCall(){
//only runs the very first iteration of this function
console.log("running..: "+localCounter);
if (localCounter == 0) {
console.log("running autonomous first time");
localCounter++;

setTimeout(function() {
localCounter++;
console.log("settimeout 1 completed");
asyncCall();
}, 0);

setTimeout(function() {
localCounter ++;
console.log("settimeout 2 completed");
asyncCall();
}, 0);
} else if (localCounter == 3){
console.log("functions have returned");
return;
}
})();

关于javascript - JS 停止控制流直到异步 setTimeout 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436543/

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