防止InternalError:过多的递归

时间:2016-08-31 11:34:02

标签: javascript loops recursion callback

我已经实现了一个递归执行的功能。因为它有时需要异步执行,所以我不能使用简单的for / while循环,需要使用递归函数调用。

在一个非常抽象的片段中,这意味着以下内容:

function doStuff(){
   // async or sync things -> depends on several circumstances
   doStuff();
}
doStuff();

这很有效。但是 - 正如您所料 - 当超过最大递归调用限制时,这会导致问题。有时我需要处理超过25,000个调用,这会导致最新的Firefox(50.0a2)中出现InternalError: too much recursion

我发现捕获InternalError并在超时时重新触发回调有效:

function doStuff(){
    // async or sync things -> depends on several circumstances
    try{
        doStuff();
    } catch(e if e instanceof InternalError){
        setTimeout(function(){
            doStuff();
        }.bind(this), 25);
    }
}
doStuff();

但这看起来很丑陋和丑陋。因此,我问自己解决这种情况的首选方法是什么 - 当你无法处理循环中的事情并需要使用递归函数调用时?

1 个答案:

答案 0 :(得分:1)

将代码转换为异步。在这种情况下,你的callstack将不会很深

function doStuff(){
   setTimeout(doStuff, 0);
}
doStuff();
相关问题