Matija Matija - 18 days ago 7
Javascript Question

stagger effect with for loop

I have problems trying to make staggered animation.
I've tried this to animate elements from array("box") with delaying every other element by 10ms.But it doesn't work with setTimeout cause "i" value is added after timeout is over.Any advice how to do that?

var box=[]
for (var i = 0; i < document.getElementsByClassName('box').length; i++){box.push(document.getElementsByClassName('box')[i])}
for (var i = 0; i < box.length; i++) {
setTimeout(function () {box[i].style.transform="translateX(150px)"},i*10)
}





Any help or advice is apprecaited, Thank you in advance.

Answer

The answer involves using a IIFE to lock in the primitive value of i at the time the setTimeout is executed.

var box=[]
for (var i = 0; i < document.getElementsByClassName('box').length; i++){box.push(document.getElementsByClassName('box')[i])}
    for (var i = 0; i < box.length; i++) {
        (function (i) {
            setTimeout(function () {box[i].style.transform="translateX(150px)"},i*10)
        }(i))  // This copies the value.
    }
Comments