Skip to content

JavaScript while loop with delay

In JavaScript, you can create a while loop with a delay using the setTimeout() function. The setTimeout() function allows you to execute a piece of code after a specified delay in milliseconds.

Note: the use of setTimeout() introduces an asynchronous behavior, allowing other code execution to continue while waiting for the delay.

JavaScript while loop with delay example

Here’s an example of a JavaScript while loop with a delay:

function loopWithDelay() {
  var counter = 0;

  function iteration() {
    console.log('Counter:', counter);
    counter++;

    // Add your condition here
    if (counter < 10) {
      setTimeout(iteration, 1000); // Delay of 1 second (1000 milliseconds)
    }
  }

  iteration(); // Start the loop
}

loopWithDelay();

Output:

JavaScript while loop with delay

In this example, the loopWithDelay() function creates a while loop that executes a delayed iteration. It starts with a counter variable set to 0. Inside the iteration() function, the counter is logged to the console, incremented by 1, and then a check is made to see if it’s less than 10.

Another example

Let’s consider a practical example of a JavaScript while loop with a delay. Suppose you want to simulate a countdown timer that counts down from a specified number of seconds to 0, with a delay of 1 second between each iteration. Here’s how you can achieve that:

function countdownTimer(seconds) {
  var counter = seconds;

  function iteration() {
    console.log('Seconds remaining:', counter);
    counter--;

    if (counter >= 0) {
      setTimeout(iteration, 1000); // Delay of 1 second (1000 milliseconds)
    } else {
      console.log('Countdown complete!');
    }
  }

  iteration(); // Start the countdown
}

countdownTimer(5); // Start the countdown from 5 seconds

Output:

countdown timer in JavaScript

The loop continues until the counter reaches 0, at which point the condition becomes false. Then, the “Countdown complete!” message is logged to indicate the end of the countdown.

You can start the countdown by calling countdownTimer() and passing the desired number of seconds as an argument. In the example above, it starts the countdown from 5 seconds.

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