0

I have a for loop which goes through an array and animates an element moving from position to position with a short delay; this works perfectly. However, when I try to change the attribute of the element after each animation, it instead changes it to the value of the last array element after the first animation.

The array essentially looks something like [{x:100, y:100},{x:200, y:200},{x:300, y:300},...]

for( let i = 0; i< arr.length; i++){
    pos = arr[i];
    $elem.delay(100)
         .animate({top: pos.y, left: pos.x}, 500, function(){
             $elem.attr('data-position-x', pos.x); 
             // other code will go here
         })
         // the element attribute is immediately set to "300", 
         // instead of 100 then 200 then 300 and so on 
}

I figure the for loop is already finished by the time the first animation is started so pos gets set to the last value in the array. The animations somehow get queued with the .delay so that pos is giving the correct values but not for the .attr inside the callback... I'm not sure how to get around this.

TL;DR - Callback function is not getting delayed inside delayed .animate

I've tried using .promise() and .then(), but that nothing has worked so far. Any thoughts?

AlexM
  • 459
  • 5
  • 15

0 Answers0