How to add delay in a loop in JavaScript?


Loops are used in JavaScript to repeat actions or iterate over a piece of data. With the aid of various techniques, we can add a delay between each iteration of the loop in order to regulate the speed of execution or produce particular temporal effects. This article will teach you how to include a delay in a java script loop and how to use it to delay the execution of a specific piece of code that is running inside one.

Let’s look at some of the examples to understand the concept better −

Example 1 - Using setTimeout()

In the below example −

  • create an array with the following elements − 1, 2, 3, 4, and 5

  • Process the array pausing one second between each iteration

  • Using the setTimeout() function the processItem() function iterates through the array, delaying each iteration by 1 s

Filename - index.html

<html>
<head>
   <title>How to add delay in a loop in JavaScript?</title>
   <script>
      function delayedLoop() {
         var items = [1, 2, 3, 4, 5];
         var delay = 1000; // 1 second

         function processItem(index) {
            // Perform some task with the current item
            console.log("Processing item:", items[index]);

            // Check if there are more items to process
            if (index < items.length - 1) {
               // Set a timeout to process the next item after the delay
               setTimeout(function () {
                  processItem(index + 1);
               }, delay);
            }
         }

         // Start the loop with the first item
         processItem(0);
      }

      delayedLoop();
   </script>
</head>
<body>
   <h3>Add Delay in Loop using setTimeout()</h3>
</body>
</html>

Output

The result will like the image below.

Example 2 - Using async/await

In this example, we will −

  • Make a function called sleep() that delivers a promise that resolves after a predetermined period of time.

  • Inside the delayedLoop() function, we will iterate over the array of items. The await sleep(delay) statement is used to introduce the delay, of 1 second, between each iteration.

Filename - index.html

<html>
<head>
   <title>How to add delay in a loop in JavaScript?</title>
   <script>
      function sleep(ms) {
         return new Promise(resolve => setTimeout(resolve, ms));
      }

      async function delayedLoop() {
         var items = [1, 2, 3, 4, 5];
         var delay = 1000; // 1 second

         for (var i = 0; i < items.length; i++) {
            // Perform some task with the current item
            console.log("Processing item:", items[i]);

            // Wait for the specified delay before processing the next item
            await sleep(delay);
         }
      }

      delayedLoop();
   </script>
</head>
<body>
   <h3>Add Delay in Loop using async/await</h3>
</body>
</html>

Output

The result will like the image below.

Conclusion

Adding a delay in a loop can be useful in various applications, such as creating timed animations, or controlling the execution speed of repetitive tasks. We learned how to add a delay in a loop in javascript using setTimeout() and async/await with a custom sleep() function and saw some examples explaining the same.

Updated on: 16-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements