Avoid Maximum call stack size exceeded in JavaScript

Overview

  • Error Maximum call stack size exceeded  is raised when calling a recursive function in a  loop
  •  This is expected – as every Javascript Engine has a maximum Call Stack Range

Failing Javascript Code

function errorFunc(rc) {
    var runCount = rc;
  var maxCount = 100000;
  if ( (rc % 5000) === 0 ) {
    logMessage("errorFunc():: Recursion Count:  " + runCount );
  } 
  runCount++;
  if (runCount >= maxCount ) {
      logMessage("errorFunc() reached MAX recursion Count :  " + runCount );
    return;
  }
  try {
      errorFunc(runCount);
      } catch (e ) {
        if ( e instanceof RangeError) {
            logMessage("errorFunc():: " + e +  ": " + runCount );
        }
      }
};

  • Output

recursionOK

Fixed Code be using setTimeout() function

  • Workraound : use setTimeout() function
  • setTimeout() function always creates a Top Level Function
function     workingFunc(rc) {
    // logMessage("workingFunc()");
  var runCount = rc;
  var maxCount = 100000;
  if ( (rc % 20000) === 0 ) {
    logMessage("workingFunc():: Recursion Count:  " + runCount );
  } 
  runCount++;
  if (runCount >= maxCount ) {
      logMessage("workingFunc() reached MAX recursion Count :  " + runCount );
    return;
  }
 
  try {
      setTimeout( workingFunc, 0, runCount);
      } catch (e ) {
        if ( e instanceof RangeError) {
            logMessage("workingFunc():: " + e +  ": " + runCount );
        }
      }
  };
  • Output of fixed CoderecursionOK
  • Note: The setTimeout() Workaorund is very slow

References

 

Leave a Reply

Your email address will not be published. Required fields are marked *