Javascript + jquery + setinterval + animation

I have a problem with setInterval and jquery aimate. Here is my code:

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

When you switch to another browser tab and return after some time, the animation continues to do this without delay, for a time when I was not on the tab, and then I act correctly. I also added them with no luck:

 $(window).focus(function () { jQuery.fx.off = false; cyc = setInterval("slides1()", 3000); }); $(window).blur(function () { jQuery.fx.off = true; window.clearInterval(cyc); }); 
+4
source share
1 answer

Newer versions of jQuery use requestAnimationFrame callbacks to handle effects, and browsers do not handle them in hidden tabs.

In the meantime, your setInterval events are still happening, which leads to an increase in the number of animations in the queue.

Instead of using setInterval to schedule the animation, use the "end callback" of the last animation to start the next loop, if necessary setTimeout .

 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 provide a close connection between the delay between sessions and the animation itself and avoid problems with setTimeout lack of synchronization with the animation.

+4
source

Source: https://habr.com/ru/post/1413374/


All Articles