I have a custom made slideshow object to perform the usual stuff the name indicates on a website. It all works well except when I switch tabs in Chrome and come back to the
There was a similar problem with chrome
As I have solved this problem. At the start, write down mktime variable, and then simply subtracted from the current time. Example:
var values = {};
function mktime(){
var date = new Date();
return Math.floor(date.getTime()/1000);
}
function getTime(string){
var splitContent = string.split(/\:/g);
var hours = parseInt(splitContent[0]) * 60 * 60;
var minutes = parseInt(splitContent[1]) * 60;
var seconds = parseInt(splitContent[2]);
return hours + minutes + seconds;
}
function startTimer(time){
values.startMkTime = mktime();
values.startTime = getTime(time);
setInterval(process(),1000);
}
function process(){
values.currentTime = (mktime() - values.startMkTime) + o.values.startTime;//new code
}
I'd favour using setTimeout() repeatedly over using setInterval() - so many things can go wrong with setInterval() and you don't know how busy the browser is and whether the interval is realistic.
Browsers don't honour your chosen timeout or interval exactly. This is mainly for security; to prevent a flood of events from messing with the browser's ability to function normally. Chrome is better about honouring timers more accurately, though it does still slow them down significantly when a tab is in the background (see this answer), for example.
If you set a new timer with setTimeout during your existing call to slideshow.action(), then you won't get events queuing up when your browser can't quite keep up, but it will still go nice and quickly when the browser is able to do so.
You will still be able to stop the timer using the timer ID, that ID will just change often.
Most likely, you shouldn't expect setInterval to ever be accurate. If I were you, I would check that the interval is correct by comparing the previous interval time to the current one. That should make the code more robust.
Chrome (and apparently the latest versions of Firefox too) reduce the speed of setInterval
when the tab is in the background to improve foreground performance. This probably matters the most when there are fast running timer-driven animations in background pages. When the page comes back to the foreground, it "tries" to catch up and runs a bunch of setInterval
calls much faster than they would normally run.
The work-arounds are:
setInterval
so Chrome won't mess with it (you'd have to look up what that time is).setTimeout
instead of setInterval
with some type of repeated setTimeout like this:Code:
function nextSlide() {
// show next slide now
// set timer for the slide after this one
setTimeout(function() {
nextSlide(); // repeat
}, xxx)
}
Similar post here.