setTimeout使用多个选项卡加速 [英] setTimeout speeds up with multiple tabs

查看:276
本文介绍了setTimeout使用多个选项卡加速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似这个。但是这个解决方案对我没有帮助,因为我不能在我的文件中使用php。

I’m having a setTimeout problem similar to this one. But that solution doesn't help me since I can’t use php in my file.

我的网站有一个滑块,其中包含每8秒移动一次的图像列表。但是,当我在浏览器中打开几个选项卡然后再切换回来时,它就变得疯狂了。
滑块继续在没有8秒延时的情况下一个接一个地移动图像。

My site has a slider with a list of images that move every 8 seconds.However, when I have opened a few tabs in the browser and then switch back again, it goes nuts. The slider proceeds to move the images one after the other immediately without the 8 second timedelay.

我只在Chrome和最新的Firefox中看到它。

I'm only seeing it in Chrome and the latest Firefox.

**编辑:我检查了console.log(),并且setTimeout在clearTimeout之前和之后返回相同的数字。不知道为什么。也许这也与它有关? **

** I checked with console.log() and the setTimeout returns the same number before and after the clearTimeout. Not sure why. Maybe that also has something to do with it? **

编辑2:我添加了一个小提琴: http://jsfiddle.net/Rembrand/qHGAq/8/

EDIT 2: I added a fiddle: http://jsfiddle.net/Rembrand/qHGAq/8/

代码如下所示:

spotlight: {
    i: 0,
   timeOutSpotlight: null,

   init: function()
   {
       $('#spotlight .controls a').click(function(e) {

           // do stuff here to count and move images

           // Don't follow the link
           e.preventDefault();

           // Clear timeout
           clearTimeout(spotlight.timeOutSpotlight);

           // Some stuff here to calculate next item

           // Call next spotlight in 8 seconds
           spotlight.timeOutSpotlight = setTimeout(function () {
                spotlight.animate(spotlight.i);
            }, 8000);
       });

       // Select first item
       $('#spotlight .controls a.next:first').trigger('click');
   },

   animate: function(i)
   {
       $('#spotlight .controls li:eq(' + (spotlight.i) + ') a.next').trigger('click');
   }
}


推荐答案

来自 jQuery文档


由于 requestAnimationFrame()的性质,你永远不应该
使用setInterval或setTimeout循环的队列动画。为了
保留CPU资源,支持requestAnimationFrame
的浏览器在不显示窗口/选项卡时不会更新动画。如果
你继续通过setInterval或setTimeout排队动画,而
动画暂停,当窗口/标签重新获得焦点时,所有排队的动画将开始播放
。为了避免这个潜在的问题,
在循环中使用上一个动画的回调,或者
函数附加到元素.queue()
设置超时以开始下一个
动画。

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.

这篇关于setTimeout使用多个选项卡加速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆