Unexpected infinite loop

This code runs for infinity, why?

    function f(n){
        i=0;
        if (n==2){
            while(i<2){
                f(i);
                i++;
            }
        }
    }

if n!=2 the function should do nothing and if n equals 2 the function calls f(0) and f(1) so it should stop after that but you only get infinite loop when you run it.

any one could tell why?

edit: there is nothing outside the function.

and no need for better code.Just asking why.

Answers:

Answer

You can fix it by changing

i=0;

to

var i=0;

Your i variable is global (or at least its scope is external to f, so it's shared by all calls of the function). When n is initially 2, you enter the loop and this loop always resets i to 0 just before the increment. The sequence you have is thus

i = 0 // start of f
// enters loop for the first time with f(0)
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
...
Answer

i is global. Declare it with var instead to keep it local to each instance. Otherwise, it is constantly reset to 0, so your while loop never ends.

Answer

Because you got f(i) all the time with i = 0. So when you are doing a loop, you are going to do f(0) indefinitly ! (same for every i) Just put a var on your i to stop your loop

Answer

Can you try this, i=0 is global variable, reason for f(i) setting the value each and every time along with Global variable, so you need to use var i=0; for initialize the i every time.

    function f(n){
        var i=0;
        if (n==2){
            while(i<2){
                f(i);
                i++;
            }
        }
    }
Answer

Every time f() is called, i is set back to 0. Since you didn't do var i = 0, that means that i is global! Every time f() is called, the same value of i is used.

When you call f(2), you start a while loop. Every time you call f(i), you are re-setting i to 0. So the while loop never ends.

You need to make i local:

function f(n){
    var i=0;
    if (n==2){
        while(i<2){
            f(i);
            i++;
        }
    }
}

This way every time f() is called, it creates its own i variable.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.