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

查看:34
本文介绍了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/

代码看起来像:

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天全站免登陆