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

标签 javascript asynchronous recursion

我正在尝试使用同步计数器和递归自调用函数来阻止控制流到我的代码的其余部分,直到设置的超时异步函数调用终止并递增我的同步计数器。然而事实证明,出于某种原因,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/

相关文章:

javascript - 使用 c9.io 设置 Node js 服务器

python - Django异步-关于模型保存功能

javascript - 如何在 JavaScript 中获取点击的 div 元素的 ID?

javascript - 根据 <td> 中的值着色 <tr>

javascript - 正确使用 express.js API,如获取、发送、重定向

python - 如何递归地增加列表中的第一个值并附加到 python 中的嵌套列表?

c# - 如何为正则表达式词干制作通用前缀?

javascript - 你如何在 promise 中返回?

flutter - 无法在dart中的then函数中将值分配给外部函数变量

swift - 使用swift递归列出文件夹中的所有文件