title: Prevent InternalError: too much recursion
body: <p>I've implemented a function that does things recursively. Because it sometimes needs to do things asynchronously, I can't use a simple <code>for</code>/<code>while</code> loop and need to use recursive function calls.</p>
  
  <p>In a very abstract snippet this would mean the following:</p>
  
  <pre><code>function doStuff(){
     // async or sync things -&gt; depends on several circumstances
     doStuff();
  }
  doStuff();
  </code></pre>
  
  <p>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 <code>InternalError: too much recursion</code> in the latest Firefox (50.0a2).</p>
  
  <p>I've found out that catching the InternalError and re-triggering the callback with a timeout works:</p>
  
  <pre><code>function doStuff(){
      // async or sync things -&gt; depends on several circumstances
      try{
          doStuff();
      } catch(e if e instanceof InternalError){
          setTimeout(function(){
              doStuff();
          }.bind(this), 25);
      }
  }
  doStuff();
  </code></pre>
  
  <p>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?</p>