Home >Web Front-end >JS Tutorial >How to Properly Implement 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.
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.
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!