第一个函数中的 setTimeout() 和 javascript 中的闭包第二个函数是否会出现堆栈溢出错误?

Is there will be any stack overflow error with setTimeout() in 1st function and closure 2nd function in javascript?

这里有没有可能工作一段时间后(经过几个小时的计算)出现stack overflow error? 或者 long 运行 这里的另一个错误?

    var timerIdPrecalculationsTurns = null;

    function precalculationsInit() {
        if (!timerIdPrecalculationsTurns) {
            timerIdPrecalculationsTurns = setTimeout(function(){
                precalculationsInitClosure();
            }, 10);
        }
    }

    function precalculationsInitClosure() {
        // make some calculations for ~20ms ...
        // and then repeat in next iteration:
        timerIdPrecalculationsTurns = null;
        precalculationsInit();
    }

    // just start the loop
    precalculationsInit();

是我用的简化版代码。但它会告诉我的问题,我希望。

有一些类似的回答,不知道是不是我的情况:

Will setTimeOut function in recursive function cause stack overflow?

JavaScript Closures and setTimeout

您的实施方式应该没有任何问题。对于此用例,我建议您使用 setInterval

不,不会。

计时器 "set aside" 回调 - 他们不会在与当前 运行(调用 setTimeout 的那个)相同的执行堆栈中调用它们。 JS 将继续执行当前脚本,直到堆栈为空,然后再调用定时器设置的任何回调(或与此相关的任何已完成的异步操作)。

在你的情况下 precalculationsInit 会 "schedule" precalculationsInitClosure,然后完成执行,清空堆栈。然后至少 10 毫秒后,JS 将调用预定的 precalculationsInitClosure,做一些事情,然后调用 precalculationsInit 并重复相同的过程。

你的堆栈看起来像:

(empty)
pI (schedules pIC)
(empty, JS looks for callbacks)
pIC
pIC -> pI (schedules pIC)
pIC
(empty, JS looks for callbacks)
pIC
pIC -> pI (schedules pIC)
pIC
(empty)
...and so on

如您所见,由于这个 "scheduling"/"setting aside",堆栈不会像递归那样堆积:

pI
pI -> pIC
pI -> pIC -> pI
pI -> pIC -> pI -> pIC
...and so on