简体   繁体   中英

Prevent InternalError: too much recursion

I've implemented a function that does things recursively. Because it sometimes needs to do things asynchronously, I can't use a simple for / while loop and need to use recursive function calls.

In a very abstract snippet this would mean the following:

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

This works great. But – as you might expect – this causes problems when the maximum recursive call limit is exceeded. Sometimes I need to handle more than 25,000 calls, which causes an InternalError: too much recursion in the latest Firefox (50.0a2).

I've found out that catching the InternalError and re-triggering the callback with a timeout works:

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();

But this looks hacky and ugly. Therefore I'm asking myself what would be the preferred way to workaround this situation – when you can't handle things in a loop and need to use recursive function calls?

Transform code to asynchronous. It this case your callstack will not be deep

function doStuff(){
   setTimeout(doStuff, 0);
}
doStuff();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM