Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery setInterval too fast when coming from another tab

I've got a site with endlessly sliding images using jquery's setIntervall() function.

When calling the page in Chrome 13 and I switch to another tab to come back a few seconds later the image sliding is happening faster, as if it tried to keep up to where it was if it hadn't switched to another tab.

How could I resolve this issue?

$(window).load(function() { 
    setInterval(nextSlide, 3500);
});

function nextSlide(){   
    offset += delta;
    $("#slideContent").animate({left: -1 * offset}, 1000);
}
like image 802
Jan Feldmann Avatar asked Jul 18 '11 17:07

Jan Feldmann


People also ask

How do you slow down setInterval?

Answer: Use the clearInterval() Method You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

When should I use clearInterval?

The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that. setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms). setInterval() executes the passed function for the given time interval.

Does setInterval execute immediately?

This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.

How can I stop setInterval after 10 seconds?

Actually, setInterval() returns an interval ID, which we pass to clearInterval() to stop that setInterval method from running the code. Thus we are being able to stop setInterval() method from running our JavaScript code after a certain time or after few seconds.


1 Answers

At the beginning I would like to apologize for all the mistakes - my English is not perfect.

The solution of your problem may be very simple:

$(window).load(function() { 
    setInterval(nextSlide, 3500);
});

function nextSlide(){   
    offset += delta;
    $("#slideContent").stop(true,true).animate({left: -1 * offset}, 1000);
}

inactive browser tabs buffer some of the setInterval or setTimeout functions. stop(true,true) - will stop all buffered events and execute immadietly only last animation. This problem will also appears in Firefox > 5.0 - read this article: Firefox 5 - changes

The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).

here you can read, how animate works - it fires setInterval function many times. How animate really works in jQuery

like image 117
nitka.pawel Avatar answered Oct 05 '22 18:10

nitka.pawel