简体   繁体   中英

Max call stack exceeded

I understand what maximum call stack exceeded is. However, is there a workaround for this for my code? Furthermore, there will be a time where it eventually will stop looping, that is when position > counter1.

var a = 0;
var b = 1;
var c;
var counter1 = 1;
var position = 0;

window.onload = function() {
    var position = prompt("Please enter the position number.","0");
    calc1();
}

function calc1() {
    if(position <= counter1) {
    c = a+b;
        counter1++;
        calc2();
    }
    else {
    callResult();
    }
}

function calc2() {
    if(position <= counter1) {
    a = b+c;
    counter1++;
    calc3();
    }
    else {
    callResult();
    }
}

function calc3() {
    if(position <= counter1) {
        b = c+a;
    counter1++;
    calc1();
    }
    else {
    callResult();
    }
}

function callResult() {
    if (position %3 == 1) {
    document.getElementById("answer").innerHTML = a;
    }
    else if (position %3 == 2) {
    document.getElementById("answer").innerHTML = b;
   }
    else {
    document.getElementById("answer").innerHTML = c;
    }
}

You should avoid recursion and use loop. Something like this:

window.onload = function() {
    var position = prompt("Please enter the position number.","0");
    maincalc();
}

function maincalc() {
    var subcalc = [ calc1, calc2, calc3 ];
    var calccount = 0;

    while(position <= counter1) {
        subcalc[ calccounter ]();
        calccounter = (calccounter +1) % 3;
    }
}

The value of position is given once and never changed.

You then check, if(position <= counter1) in each call calc1 , calc2 , calc3 which call each other thus:

calc1 -> calc2 -> calc3 -> calc1 -> ...

This will clearly continue until you run out of stack space.

Perhaps if you increment position instead of counter1 or keep calling while position is greater than the counter this problem will go away, ie

if(position > counter1)

You probably need to step back and think about what you are really trying to do.

as I understand you are calculating Fibonacci numbers sum?

see this Javascript Fibonacci answer to learn how to do it much easier and without any recursive calls

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