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 (;;) {}
Related videos on Youtube
Author by
Elise Chant
Updated on July 09, 2022Comments
-
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++) {}
-
Derek 朕會功夫 almost 10 years
while(1){}
works in almost all programming languages. -
rolfl almost 5 yearsThis question is not a duplicate of stackoverflow.com/questions/5835126/javascript-infinite-loop ... even though the titles are similar
-
-
nunop over 7 yearsWon't this throw an exception?
-
alexgula over 7 yearsThat is better than while(true){}: if you use ESLint, it won't trigger eslint.org/docs/rules/no-constant-condition.
-
Alberto S. almost 7 yearsThis 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 over 6 yearsFor 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 almost 5 yearsThis one seems a better choice, since some code optimizers (like Webpack Terser plugin) spam with warnings like
Condition always false
andDropping unreachable code
when using thewhile (true)
variant. -
JoseLinares over 4 years@Alberto Except if you are not programming for browsers
-
T.CK over 4 yearsYou can break
for(;;) {}
loops withtrue
between the semicolonsfor(;true;) { if(condition) break; //do work }
. -
Denis Giffeler about 4 years@Alberto It's absolutely ok inside generator functions.
-
gilad905 about 3 yearsI like it just because it's unique :D
-
Ravindu Sachintha about 3 yearsIn 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/…)