Jquery setInterval on minimize

梦想与她 提交于 2019-12-24 09:08:14

问题


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");


来源:https://stackoverflow.com/questions/7739657/jquery-setinterval-on-minimize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!