Home > Web Front-end > JS Tutorial > How Can I Introduce a Delay into a JavaScript Loop?

How Can I Introduce a Delay into a JavaScript Loop?

DDD
Release: 2024-12-18 10:22:11
Original
787 people have browsed it

How Can I Introduce a Delay into a JavaScript Loop?

Delaying a JavaScript Loop

It's possible to introduce a delay into a JavaScript loop using the setTimeout() function. However, the default behavior of setTimeout() is to execute immediately. To introduce a delay, we need to use a recursive loop.

One way to achieve this is to use a for loop and call setTimeout() within the loop. However, this approach runs into a problem because all the setTimeouts will be scheduled immediately, leading to multiple alerts appearing at once.

To solve this, we need to use a recursive function that calls itself with a delay. The following code demonstrates this approach:

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
Copy after login

In this code, we create a recursive function called myLoop() that contains a 3-second setTimeout(). Within the timeout, we increment the counter and check if it's less than 10. If so, we call myLoop() again, thus introducing a delay between each alert.

The above is the detailed content of How Can I Introduce a Delay into a JavaScript Loop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template