setInterval有时是双倍的 [英] setInterval double times on occasion

查看:153
本文介绍了setInterval有时是双倍的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JQuery创建了一个幻灯片脚本,我正在使用setInterval(我也尝试使用setTimeout并得到了同样的问题)。问题是,当我进入一个新选项卡并回到我的页面时,幻灯片显示在幻灯片上似乎是双速。有时它甚至会减速并恢复正常速度。我很困惑为什么会这样做。请注意我此时只在FF中试过这个。

I've made a slideshow script with JQuery and I'm using setInterval (I tried with setTimeout also and got the same issue). The problem is when I go to a new tab and come back to my page with the slideshow on it the slideshow seems to be going at double speed. Some times it even slows down and gets back to normal speed. I'm quite confused as to why it does this. Please note I have only tried this in FF at this time.

pictureAmount = 4;
fadeSpeed = 600;
delay = 6000;
heightOfPicture = 320; //px

function nextSlide(count) {
    $('#slide-link').fadeOut(fadeSpeed, 'linear', function () {
        document.getElementById('slide-link').style.backgroundPosition = '0 -' + (heightOfPicture * count) + 'px';
    }).fadeIn(fadeSpeed, 'linear');
}

count = 0;
window.setInterval(function () {
    if (++count >= pictureAmount) count = 0;

    nextSlide(count);
}, delay);

这是链接 http://mprodesigns.com/new

推荐答案

你所看到的是一个常见的更新的浏览器中的(以及相当新的)行为。页面处于非活动状态时,它们会降低计时器的速度当你回到页面时,计时器赶上。

What you're seeing is a common (and fairly new) behavior in updated browsers. They slow down your timers when pages are inactive. When you get back to the page, the timer "catches up".

这有助于完全避免setInterval()并改为使用setTimeout()。让自己的代码在每次唤醒时重新设置超时。这样,你就不会有很多待处理的调用程序调用。

It helps to just avoid "setInterval()" entirely and use "setTimeout()" instead. Have your own code re-set the timeout on each wakeup. That way, you won't have lots of pending handler invocations to run.

所以你可以这样做而不是setInterval():

So instead of "setInterval()" you can do this:

function timerHandler() {
  if (++count >= pictureAmount) count = 0;
  nextSlide(count);
  setTimeout(timerHandler, delay);
}

setTimeout(timerHandler, delay);

通过提高最小延迟时间来实现减速效果。通常,当您专注于窗口时,它就像10或15毫秒。但是,当选项卡/窗口没有聚焦时,它就像1000毫秒。

The "slow down" effect is imposed by upping the minimum delay time. Normally, when you have focus on the window, it's like 10 or 15 milliseconds. When the tab/window is not focused, however, it's like 1000 milliseconds.

编辑这是一个演示页,如果您退出标签并返回标签页,则不应显示异常加速。

edit — Here is a demonstration page which should not show an anomalous speed-up if you leave the tab and return to it.

这篇关于setInterval有时是双倍的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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