how do I create an infinite loop in JavaScript

144,511

Solution 1

You can also use a while loop:

while (true) {
    //your code
}

Solution 2

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}
Share:
144,511

Related videos on Youtube

Elise Chant
Author by

Elise Chant

Updated on July 09, 2022

Comments

  • Elise Chant
    Elise Chant almost 2 years

    I want to create an infinite loop in JavaScript.

    What are some ways to achieve this:

    eg

    for (var i=0; i<Infinity; i++) {}
    
  • nunop
    nunop over 7 years
    Won't this throw an exception?
  • alexgula
    alexgula over 7 years
    That is better than while(true){}: if you use ESLint, it won't trigger eslint.org/docs/rules/no-constant-condition.
  • Alberto S.
    Alberto S. almost 7 years
    This will block the Javascript execution in the page, leading to a browser dialog asking to stop or debug the script. It won't work
  • counterbeing
    counterbeing over 6 years
    For some reason, I just hate how this looks in my code. So cryptic. I wonder if there's a more semantic way to do it? But yeah, seems like the way to go in this case!
  • ololoepepe
    ololoepepe almost 5 years
    This one seems a better choice, since some code optimizers (like Webpack Terser plugin) spam with warnings like Condition always false and Dropping unreachable code when using the while (true) variant.
  • JoseLinares
    JoseLinares over 4 years
    @Alberto Except if you are not programming for browsers
  • T.CK
    T.CK over 4 years
    You can break for(;;) {} loops with true between the semicolons for(;true;) { if(condition) break; //do work }.
  • Denis Giffeler
    Denis Giffeler about 4 years
    @Alberto It's absolutely ok inside generator functions.
  • gilad905
    gilad905 about 3 years
    I like it just because it's unique :D
  • Ravindu Sachintha
    Ravindu Sachintha about 3 years
    In a case, if it is expected to execute in a browser, a better way to implement an infinite loop Is using setTimeout or setInterval function. This post contains more descriptive details about that. (nextcsguide.com/javascript/…)