53

I want to create an infinite loop in JavaScript.

What are some ways to achieve this:

eg

for (var i=0; i<Infinity; i++) {}
Elise Chant
  • 5,048
  • 3
  • 29
  • 36

2 Answers2

79

You can also use a while loop:

while (true) {
    //your code
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Pran
  • 831
  • 6
  • 8
74

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

for (;;) {}
Elise Chant
  • 5,048
  • 3
  • 29
  • 36
  • 5
    That is better than while(true){}: if you use ESLint, it won't trigger http://eslint.org/docs/rules/no-constant-condition. – alexgula Oct 10 '16 at 10:30
  • 4
    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! – counterbeing Nov 08 '17 at 21:17
  • 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. – ololoepepe Jul 06 '19 at 15:39
  • 3
    You can break `for(;;) {}` loops with `true` between the semicolons `for(;true;) { if(condition) break; //do work }`. – T.CK Dec 13 '19 at 16:14
  • I like it just because it's unique :D – gilad905 Mar 23 '21 at 21:51