Home >Web Front-end >JS Tutorial >How to Properly Implement a Delay in a JavaScript Loop?

How to Properly Implement a Delay in a JavaScript Loop?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 05:15:13807browse

How to Properly Implement a Delay in a JavaScript Loop?

Adding a Delay in a JavaScript Loop

In JavaScript, it is common to encounter scenarios where a delay is required within a loop to control the execution pace. However, implementing this delay can be tricky.

Original Approach and Its Pitfalls

Initially, the code below was used in an attempt to introduce a 3-second delay for each iteration of the loop:

alert('hi');

for(var start = 1; start < 10; start++) {
  setTimeout(function () {
    alert('hello');
  }, 3000);
}

However, this approach failed to achieve the intended result because the setTimeout() function is non-blocking. As a result, the loop executed rapidly, initiating multiple 3-second timeout triggers in quick succession. This led to the first alert('hello') popup appearing after 3 seconds, followed by a constant stream of alert('hello') popups without any delay.

Resolving the Delay Issue

To address this issue, it is recommended to employ the following approach:

var i = 1;                  // Set counter to 1

function myLoop() {         // Create loop function
  setTimeout(function() {   // Call 3s setTimeout when loop is called
    console.log('hello');   // Your code here
    i++;                    // Increment counter
    if (i < 10) {           // If counter < 10, call loop function
      myLoop();             // .. again, triggering another 
    }                       // .. setTimeout()
  }, 3000)
}

myLoop();                   // Start the loop

This revised approach utilizes a recursive function, myLoop(), which initiates a 3-second setTimeout() whenever the function is called. By incrementing the counter i within the setTimeout() callback, the function can continue the loop iteration after the delay. This ensures that subsequent iterations of the loop wait the specified time before executing.

The above is the detailed content of How to Properly Implement a Delay in a JavaScript Loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn