1

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);
}
Zach
  • 51
  • 1
  • 9
  • 4
    Use `setTimeout(function() {testArray[i].style.opacity = ".5"}, 500*(i+1));` – Vinay Feb 20 '17 at 05:37
  • In case you get stuck -https://jsfiddle.net/xjLjt42z/ – Vinay Feb 20 '17 at 05:44
  • @Novice You can add that as an answer. This seems like something that would have been asked here before, but I can't find a good duplicate. – JLRishe Feb 20 '17 at 05:46
  • @Novice not sure how to set comments as answers, but thanks that helped a lot! I looked around a bunch and I couldn't find that answer anywhere! – Zach Feb 20 '17 at 06:15
  • Sorry for replying a bit late I was busy for a while .Since you couldn't find any duplicate I've added my answer – Vinay Feb 20 '17 at 10:48

3 Answers3

2

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

Vinay
  • 7,442
  • 6
  • 25
  • 48
0

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);
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
0

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

Kishan Oza
  • 1,707
  • 1
  • 16
  • 38