Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is setInterval() and setTimeout() bad things to do in modern jQuery animations?

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.

like image 980
Dexy_Wolf Avatar asked Dec 17 '22 10:12

Dexy_Wolf


1 Answers

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.

like image 111
martin Avatar answered Jan 12 '23 00:01

martin