Unexpected infinite loop

infinite-loop, javascript

Solution

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++
...

Problem

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.

Original source