Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

406
Views
Why setInterval inside a while loop become an infinite loop (JS)?

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);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!