开发者

setInterval double times on occasion

开发者 https://www.devze.com 2023-03-16 23:58 出处:网络
I\'ve made a slideshow script with JQ开发者_如何学Cuery 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

I've made a slideshow script with JQ开发者_如何学Cuery 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);

Here is the link 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".

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.

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

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

setTimeout(timerHandler, delay);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号