4

I had some problems with animations with jQuery 1.6. I solved it with jQuery 1.5.

In my project I used setInterval() to make custom logo slider. Animations fired up instantly (not simultaneously) two by two. Everything goes smoothly when I am on the page, but when I went on other tab and comeback (after minute, two or so) to my page project everything goes crazy...

Ok, so I got one answer to use Queue(). Can I achieve same thing with that method?

I have book Manning jQuery in Action and there is nothing on instantly fired up animations with Queue().

Link to Jsfiddle

To quote some of that answer:

Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop.

Dexy_Wolf
  • 989
  • 3
  • 13
  • 25
  • I had something similar happen on one of my pages. I solved it by `.stop()`ing all active animations at the beginning of each interval. – Shad Aug 22 '11 at 00:59
  • Different browsers handle timers differently with regard to what happens when your tab loses focus, e.g., some may temporarily suspend your `setInterval`; some may queue everything and then try to catch up when your tab gets focus again - sounds like this is what is happening to you. – nnnnnn Aug 22 '11 at 01:00
  • @nnnnnn But with jQuery 1.5 there is no problem... I canceled UI effects and come back to `animate()`, but I suspect that will fix and UI effects. – Dexy_Wolf Aug 22 '11 at 01:01

1 Answers1

13

In general setInterval == BAD and setTimeout == GOOD for animations.

setInterval will try play catchup, as nnnnnn stated:

some browsers may queue everything and then try to catch up when your tab gets focus again

You best method for looping animate() is by calling recursively, for example:

var myTimeout;

var myAnimation = function () {

    $('#myID').animate({
        [propertyKey]:[propertyValue]
    }, 5000, function() {
        myTimeout = setTimeOut(myAnimation, 1000);
    });
}

Notice how the myTimeout is held outside the scope of myAnnimation allowing the ability to stop the animation

clearTimeout(myTimeout);

Which you could hook up to the window.unload event.

martin
  • 2,493
  • 1
  • 20
  • 13
  • Kinda, issue #9381 is the same window.unload problem, however using setInterval() will only exacerbate if further - You should always keep track of your animations. Unless you need a timer that plays catchup then setInterval is still evil. – martin Aug 22 '11 at 06:32