Zach
Zach

Reputation: 51

Set a delay between each element in an array using a for loop

I'm trying to change the opacity of each element in an array but with a slight delay between each element. I've tried a bunch of variations of the simplified code snippet below but each time either they all change at once with a delay or nothing changes. Whats the correct syntax for this code?

for (let i = 0; i < testArray.length; i++) {
  setTimeout(function() {testArray[i].style.opacity = ".5"}, 500);
}

Upvotes: 1

Views: 126

Answers (3)

Vinay
Vinay

Reputation: 7676

Since you're using let asynchronicity is not the issue here rather it's just timing.You just need to change

 setTimeout(function() {testArray[i].style.opacity = ".5"}, 500);

To

 setTimeout(function() {testArray[i].style.opacity = ".5"}, 500*(i+1));

This would set timer for items in increasing amounts of 500 ms like 500,1000,1500 and so on

Upvotes: 2

Kishan Oza
Kishan Oza

Reputation: 1735

you can use $('').slideUp(2000); method to delay between your two element i used this several times.its works fine

Upvotes: 0

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

Try using setInterval in case it didn't work with setTimeout like the following :

   var counter = 0;
   var arrayLength =testArray.length;
   var refOfSetInterval;

   function changeOpacity(){
    if(counter < arrayLength){
    testArray[counter].style.opacity = ".5";
    counter++;
    }
    else{
    clearInterval(refOfSetInterval);
    }
   }

  refOfSetInterval = setInterval(changeOpacity,1000);

Upvotes: 0

Related Questions