Modern browsers suspend some Javascript codes, such as setTimeout
, when the window is not in focus to save power and processing resources. Imagine if you were running Javascript when you minimized your mobile browser.
One solution is to create a Loginer for some Hooks. For example, when focus is lost from the tab, you save time and when focus returns you subtract and see how much time has passed to adjust your timer.
To check these Hooks, you can make use of the Page Visibility API, described on MDN.
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var videoElement = document.getElementById("videoElement");
// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if (document[hidden]) {
videoElement.pause();
} else {
videoElement.play();
}
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || typeof document.hidden === "undefined") {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
// When the video pauses, set the title.
// This shows the paused
videoElement.addEventListener("pause", function(){
document.title = 'Paused';
}, false);
// When the video plays, set the title.
videoElement.addEventListener("play", function(){
document.title = 'Playing';
}, false);
}
Timeouts in inactive tabs throttled to >=1000ms
To reduce the load (and Associated Battery Usage) from background
tabs, timeouts are throttled to Firing no more often than Once per
Second (1000 ms) in inactive tabs.
Firefox Implements this behavior Since version 5 (see bug 633421, the
1000ms Constant can be tweaked through the
dom.min_background_timeout_value preference). Chrome Mplements this
behavior Since version 11 (crbug.com/66078).
Firefox for Android uses a timeout value of 15 minutes for background
tabs Since bug 736602 in Firefox 14, and background tabs can also be
unloaded entirely.
taken from the Mozilla Developers Network
my timer and a simple increment variable as I can "calculate" the time the tab was out of focus if javascript will be "paused"?
– RFL