为什么setTimeout适用于无休止的递归调用

Why does setTimeout works for endless recursive calls?

本文关键字:递归 调用 无休止 setTimeout 适用于 为什么      更新时间:2023-09-26

这是我的递归函数:

function importTEI(index,data,header){
    if (index == data.length){return}
    var tei = new dhis2API.trackedEntityInstance();
    tei.excelImportPopulator(header,data[index]);
    tei.POST(requestCallback,requestCallback,index);
    function requestCallback(response){
        notificationCallback(response);
        setTimeout(function(){
            importTEI(response.importStat.index+1,importData,header);
        },0);
    }
}

函数importTEI在函数内使用setTimeout调用。当在没有setTimeout的情况下调用时,在几次请求后会出现此错误-

Uncaught RangeError: Maximum call stack size exceeded

但有了setTimeout,它将永远运行。。。。为什么?setTimeout内部发生了什么特别的事情?它不再是递归调用了吗?

任何提示都将不胜感激。Thnx。

它不再是递归调用。setTimeout是将来的回调,该调用将位于"堆栈顶部"。对函数的现有调用设置此回调,然后完成其执行,从而导致零递归。

setTimeout函数只能工作一次。查看您的代码。在startTime函数中,您将在0毫秒后再次调用同一个函数。如果希望它重复一段时间,请改用setInterval。此函数返回一个id,您可以使用该id随时停止它。

请参考以下答案:为什么setTimeout函数会永远执行?