简体   繁体   中英

How to add a delay in a JavaScript loop before the next iteration?

[Solved thanks to the best answer here]

The page is now finished and works smoothly. Take a look at the result on codepen:

https://codepen.io/Lietsaki/pen/pXOeKO


I'm making a simple website that contains some information about the Doge meme. I want some phrases to pop up in every section, so I added a class with "display: none" and set up some events in JS to remove the classes as the user clicks on the next section.

However, so far I've only been able to remove all classes at once instead of one class being removed every n seconds.

I've tried using a for loop with setInterval, but it didn't work. So I tried making a function that loops until a condition is met with setTimeout, but that removes all classes at once and throws a console error:

"Uncaught TypeError: Cannot read property 'classList' of undefined at addPhrase (whoisdoge.js:78) at whoisdoge.js:83"

Please check the code below.

// Select the phrases with the class ".phrase1"

var phrase1 = document.querySelectorAll(".phrase1");

// Turn it into an array and get its length(30) into a variable
var phrase1Arr = Array.from(phrase1);


// Function to remove a class every 3 seconds (NOT WORKING)

function addPhrase(l){

    phrase1Arr[l].classList.remove("disappear");

    if (l < 30){
       setTimeout(function(){
           l++;
           addPhrase(l)
       }, 3000);
    }

}

Your function is breaking because you're trying to remove index 30 when there are only 30 elements in your array. (So you're trying to remove the 31st element)

You should move your remove into the same if statement that you already have.

function addPhrase(l){
  if (l < 30){
    phrase1Arr[l].classList.remove("disappear");
    setTimeout(function(){
      l++;
      addPhrase(l)
    }, 3000);
  }
}

You're also calling a function instead of referencing a function in your addEventListener calls:

sec0[0].addEventListener("click", addPhrase(0));

Should be

sec0[0].addEventListener("click", function(){
   addPhrase(0)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM