Home > Net >  Why setInterval inside a while loop become an infinite loop (JS)?
Why setInterval inside a while loop become an infinite loop (JS)?

Time:03-18

I tried to call a delayed "one" call or a "one or two?" question, but instead the function started running indefinitely, although without setInterval everything worked fine.

quester2()
function quester2() {
  for (i = 0; i <= finalCount; i  ) {
    let K = Math.ceil(Math.random() * 2);
    if (K == 1) {
      setInterval(function () { console.log("one"); }, 1000);
      finalCount  = 1;
      allIterations  = 1;
      setInterval(function () { console.log("one or two?"); }, 1000);
    } else {
      setInterval(function () { console.log("one or two?"); }, 1000);
      allIterations  = 1;
    }
  }
  console.log(finalCount);
  console.log(i);
}

CodePudding user response:

There is no infinite loop, your code may just randomly take more iterations compared to previous runs. You sometimes increase finalCount which is involved in the condition of the for loop.

What may appear like an infinite loop is the fact that you run quite a lot of setIntervals and never clear them. But if you carefully check your console you basically instantly after invoking the function see two outputs for the last two log statements. A second after that you start seeing an infinite number of "one" and "one or two?".

quester2()

0
1
one or two?

  • Related