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);
}
5
  • 4
    Use setTimeout(function() {testArray[i].style.opacity = ".5"}, 500*(i+1)); Commented Feb 20, 2017 at 5:37
  • In case you get stuck -jsfiddle.net/xjLjt42z Commented Feb 20, 2017 at 5: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. Commented Feb 20, 2017 at 5: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! Commented Feb 20, 2017 at 6: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 Commented Feb 20, 2017 at 10:48

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.