Search code examples
javascriptfunction-call

how can I call a recursive function that calls more than 50k times in javascript?



I know the Browser Javascript Stack size limit, but is there any way to break it? while I am reading Javascript Stack size limit in net, I can not find a way to overcome the browser Stack size limit. Is there any tricks to do it in java-script or angular.

for example

var i=0;
rec(para);
function rec(para){
          if(para>=50000){

          }
          else{
            $scope.items.push(i);
            rec(i++)
          }

    }

is it possible to add 50000 data into an array..


Solution

  • Use asynchronous means

    function func1(n, callback)
    {
       //do some work
    
       //check for exit condition
       if (n == 1)
       {
         callback();// invoke callback handler and pass the results to it.
       }
       else
       {
          setTimeout(function(){
             func1(); //call it again with modified parameters
          });
       }
    }
    

    One downside is that you won't be able to return the value from this method anymore.

    is it possible to add 50000 data into an array..

    Yes, by Iteration. In your case, you simply need to do

    function rec()
    {
      for( var counter = 0; counter < 50000; counter++ )
      { 
        $scope.items.push(counter);
      }
    }