4

I'm having a problem with setInterval and jquery animate. Here is my code:

function slides1() { ... $("table#agah1").animate({ "left": first1 }, "slow"); $("table#agah2").animate({ "left": first2 }, "slow"); } $(function () { cyc = setInterval("slides1()", 3000); }); 

When switch to another browser tab, and return after a time, the animation keep doing it without delay, for the time I've been away from the tab, and then act correct. I've added these also without any luck:

$(window).focus(function () { jQuery.fx.off = false; cyc = setInterval("slides1()", 3000); }); $(window).blur(function () { jQuery.fx.off = true; window.clearInterval(cyc); }); 
1
  • 1
    not the issue here, but pass a function reference, don't pass strings. Commented May 20, 2012 at 6:32

1 Answer 1

4

Newer versions of jQuery use requestAnimationFrame callbacks to handle effects, and browsers don't process those on hidden tabs.

In the meantime, your setInterval events are still happening, causing more animations to get queued up.

Rather than use setInterval to schedule the animations, use the "completion callback" of the last animation to trigger the next cycle, with a setTimeout if necessary.

function slides1() { ... $("table#agah1").animate({ "left": first1 }, "slow"); $("table#agah2").animate({ "left": first2 }, "slow", function() { setTimeout(slides1, 2000); // start again 2s after this finishes }); } $(function () { setTimeout(slides1, 3000); // nb: not "slides1()" }); 

This will ensure that there's a tight coupling between the interanimation delay and the animations themselves, and avoid any issues with setTimeout getting out of sync with the animations.

Sign up to request clarification or add additional context in comments.

4 Comments

requestAnimationFrame is not an option. it had many bugs, and still wont work like a charm in cross browsers:bugs.jquery.com/ticket/9381
@HabibS ah - I didn't spot that they had reverted that. In any event the code above is preferable - it couples together the animation and the timeouts in a way that should prevent the problem you're seeing.
@HabibS in any event, your question is unclear. Do you want the animations to start from scratch whenever you switch tab?
Your second suggestion actually worked. The problem is that all jquery animation/fade/... commands + setinterval will be on hold if page blur occure, and will do all the loop without delay after page focus.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.