Reputation: 51
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
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
Reputation: 1735
you can use $('').slideUp(2000);
method to delay between your two element i used this several times.its works fine
Upvotes: 0
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