-->

Jquery setInterval on minimize

2019-08-01 15:19发布

问题:

I have image slider where images replace each other by timeout. I use jQuery function setInterval() but there is a small problem, after minimizing browser windows this function keep "working", and where I restore browser window images replace each other with incrediable high speed, like the whole time after window was minimized setInterval() collect actions but executing them after restoring the window.

How to pause setInterval() on browser minimize or keep swap images when windows is minimized?

回答1:

The documentation for animate() explicitly mentions:

Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop. In order to preserve CPU resources, browsers that support requestAnimationFrame will not update animations when the window/tab is not displayed. If you continue to queue animations via setInterval or setTimeout while animation is paused, all of the queued animations will begin playing when the window/tab regains focus. To avoid this potential problem, use the callback of your last animation in the loop, or append a function to the elements .queue() to set the timeout to start the next animation.

So, you can either call setTimeout() in the callback of your animation to chain the next cycle, if possible, or queue() the calls to setTimeout() between the calls to animate().

EDIT: As requested in comments, here is a simple queue() example. The code below enforces a two-second delay between the slide animations:

$("selector").slideUp("slow").queue(function(next) {
    window.setTimeout(next, 2000);
}).slideDown("slow");