Home >Web Front-end >JS Tutorial >How to Properly Add Delays to JavaScript Loops Using setTimeout()?

How to Properly Add Delays to JavaScript Loops Using setTimeout()?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 11:33:09517browse

How to Properly Add Delays to JavaScript Loops Using setTimeout()?

How to Add a Delay in a JavaScript Loop with Timeouts

In JavaScript, adding a delay within a loop can be achieved using the setTimeout() function. However, it's important to understand its behavior to avoid unexpected results.

Consider the following example:

alert('hi');

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

This code aims to show an alert with the text "hi" and then display the text "hello" after a 3-second delay, with the delay repeating for subsequent iterations. However, in practice, only the first iteration works as intended.

The reason for this behavior lies in the non-blocking nature of setTimeout(). It triggers a timer but returns immediately, allowing the loop to continue executing before the 3-second delay can occur. This results in an immediate alert of "hello" and subsequent alerts being continuously displayed without any delay.

To achieve the desired effect, an alternative approach can be used:

var i = 1; // set your counter to 1

function myLoop() { // create a loop function
  setTimeout(function() { // call a 3s setTimeout when the loop is called
    console.log('hello'); // your code here
    i++; // increment the counter
    if (i < 10) { // if the counter < 10, call the loop function
      myLoop(); // .. again which will trigger another 
    } // .. setTimeout()
  }, 3000);
}

myLoop(); // start the loop

In this approach, a counter is initialized and incremented within the loop. The loop function is called inside the setTimeout(), ensuring that each iteration has its own 3-second delay before executing. By maintaining the loop within the callback of setTimeout(), the desired interval between alerts is achieved.

The above is the detailed content of How to Properly Add Delays to JavaScript Loops Using setTimeout()?. 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