48

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
  • 4,857
  • 3
  • 26
  • 36

2 Answers2

73

You can also use a while loop:

while (true) {
    //your code
}
Adrian Mole
  • 43,040
  • 110
  • 45
  • 72
Pran
  • 761
  • 5
  • 8
67

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

for (;;) {}
Elise Chant
  • 4,857
  • 3
  • 26
  • 36
  • 3
    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
  • 3
    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
  • 2
    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