More modern browsers suspend some JavaScript code, such as setTimeout
, when the window is not in focus to save energy and processing resources. Imagine if you were running JavaScript when you minimized your browser on your phone.
One solution is to create a listener 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 in 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 than eleven
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 implements 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.
removed from the Mozilla Developers Network