1
votes

I want to use recursion to calculate the sum of from 1 to 100000,but when I run the followings code,the browser throw a exception(Uncaught RangeError: Maximum call stack size exceeded).

code:

function sum(num){
  if(num > 0){
    num +=arguments.callee(num-1);
  }
  return num;
};
sum(100000);
then,I use the followings function to calculate the times can be used in recursion.

    function computeMaxCallStackSize() {
    try {
        return 1 + computeMaxCallStackSize();
    } catch (e) {
        // Call stack overflow
        return 1;
    }
};computeMaxCallStackSize();//output:15624
so,when I use recursion to calculate more than 15624 times,what should I do?
1
Don't use recursion? Looping would be much more ideal, and I don't see a reason for recursion, unless you're learning about it - Andrew Li
Q: "Doctor, it hurts when I do that!". Reply: "Well, don't do that!" - paulsm4
In the case that you are learning, it's a good experience that shows you recursion isn't always the right way to go. The call stack is only so large, and any recursive solution can be written iteratively. - Andrew Li
sum = n => (n * n + n) / 2; seems like it'd be more efficient... - zzzzBov
I use recursion and arguments.callee just for learning.Thank everybody for the hospitable help. - GoDotDotDot

1 Answers

1
votes

You are getting too much recursion. This is browser specific, not only the stack size, but also optimizations, things like tail recursion optimization and stuff. I guess the only reliable thing here is to code in a way that doesn't put tons of stuff into the stack, or manually testing(reading deep into the documentation of) each browser. After all, when you see the "too much recursion" error or similar you already know there's something really wrong with your code.

Here's what you can do to avoid too many recursion:

  • Use iteration instead of recursion ;
  • Use Memoization ;
  • Use SetTimeOut