Alireza Valizade Alireza Valizade - 1 month ago 9
Javascript Question

setTimeout in foreach elements not working

I want

translate
the all elements in my slider but want each element
translate
with a delay,i have this idea , this is my code :

this.button_right.addEventListener( "click", function( e ) {

e.preventDefault();
self.items.forEach(function (element,index) {

setTimeout(function(){
element.style.transform = 'translate(-150px, 0)';
},1000);

});

});


any body have better idea?

Answer

Multiply delay with index

this.button_right.addEventListener("click", function(e) {
  e.preventDefault();
  self.items.forEach(function(element, index) {
    setTimeout(function() {
      element.style.transform = 'translate(-150px, 0)';
    }, (1000 * (index + 1)));
  });
});
Comments