'JavaScript animation lag after several loops

I am animating these dotted lines (SVG) for a project using velocity.js.

However, after a few loops, the animation starts to lag a lot.

I have pasted the link to my animation in the codepen below.

http://codepen.io/aofaoin/pen/pbLvAb?editors=0110

for (i = 1; i <= 69; i++) {
    $("#gold2 .cls-" + i)
      .velocity("fadeOut", {
        delay: g2,
        duration: 800,
      })
      .velocity("fadeIn", {
        delay: 15,
        duration: 800,
      })
    g2 += 80;
  }

I can't use loop:true as i want to orchestrate/choreography the animation.

It would be great if anyone can tell me how can I stop the animation from lagging after a few loops. Thank you!



Solution 1:[1]

Looking at your code, I suggest wrapping your velocity manipulation inside of setTimeout(function() { ... }, 0). This will prevent browser from freezes caused by a big number of sync operations you try to do.

  for (i = 1; i <= 69; i++) {
    setTimeout(function() {
      $("#gold2 .cls-" + i)
        .velocity("fadeOut", {
          delay: g2,
          duration: 800,
        })
        .velocity("fadeIn", {
          delay: 15,
          duration: 800,
        });
       g2 += 80;
     }, 0);
  }

If you need to do your animation with delay, add dedicated delay in setTimeout.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Appeiron