Skip to content

JavaScript infinite loop

  • by

An infinite loop in JavaScript is a loop that keeps running indefinitely, without any termination condition. This can cause your program to hang or freeze, making it unresponsive. It’s important to avoid creating infinite loops unintentionally, as they can have serious consequences.

To create an infinite loop in JavaScript, you can use different loop constructs such as while, for, or do-while. Here’s the syntax for each of these constructs to create an infinite loop:

1. Using a while loop:

while (true) {
  // Code that will execute indefinitely

2. Using a for loop:

for (;;) {
  // Code that will execute indefinitely

3. Using a do-while loop:

do {
  // Code that will execute indefinitely
} while (true);

In all of these examples, the condition that controls the loop is set to true, which means the loop will continue running indefinitely. Without any way to make the condition evaluate to false, the loop will keep executing forever unless the program is interrupted externally.

Remember to use infinite loops with caution, as they can lead to unresponsive programs and should generally be avoided.

JavaScript infinite loop example

Here’s an example of an infinite loop in JavaScript using a while loop:

while (true) {
  console.log("This is an infinite loop!");

How an infinite loop can be used in a controlled manner within a specific context.

var i = 0;

while (i >= 0) {
  console.log("Count: " + i);
  // Simulating a long-running process
  for (var j = 0; j < 100000; j++) {
    // Perform some computation


JavaScript infinite loop

In this example, the loop condition i >= 0 is always true, which means the loop will continue running indefinitely. However, inside the loop, there is a simulated long-running process represented by the inner for loop. This inner loop performs some computation 100,000 times before incrementing the variable i. This is done to introduce a delay and allow for some control within the infinite loop.

Comment if you have any doubts or suggestions on this JS Loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *