Skip to content

JavaScript infinite loop with delay

  • by

In JavaScript, you can create an infinite loop with a delay using the setTimeout or setInterval functions. These functions allow you to execute a piece of code repeatedly with a specified delay between each iteration.

JavaScript infinite loop with delay example

Here’s an example of an infinite loop with a delay of 1 second (1000 milliseconds) between each iteration:

function infiniteLoop() {
  console.log("Loop iteration");

  setTimeout(infiniteLoop, 1000); // Call the function again after 1 second
}

// Start the loop
infiniteLoop();

Output:

JavaScript infinite loop with delay

The setTimeout() function is used to schedule the next iteration of the loop after a specified delay. In this case, it’s set to 1000 milliseconds (1 second), but you can adjust the delay as per your requirement.

By calling setTimeout(infiniteLoop, 1000) at the end of the function, you ensure that the infiniteLoop() function will be called again after the specified delay, creating an infinite loop with a delay between iterations.

Comment if you have any doubts or suggestions on this JS infinite 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 *