I have a few setTimeout functions in my project each with a setInterval.
From what I\'ve experienced setInterval stops when I\'m leaving the window, however, setTimeout
You can watch for when a tab loses focus by using the event listener visibilitychange
. When the visibility changes, you can use document.hidden
to see if the document is hidden. If it is you can then clear the timeout. When it regains focus, you can call setTimeout
to resume function.
let myTimeout = null
function timeoutfunction() {
console.log('timeout called')
myTimeout = setTimeout(timeoutfunction, 1000)
}
function onVisibilityChanged() {
if (document.hidden || document.mozHidden || document.webkitHidden || document.msHidden) {
// The tab has lost focus
clearTimeout(myTimeout)
} else {
// The tab has gained focus
myTimeout = setTimeout(timeoutfunction, 1000)
}
}
document.addEventListener("visibilitychange", onVisibilityChanged, false);
document.addEventListener("mozvisibilitychange", onVisibilityChanged, false);
document.addEventListener("webkitvisibilitychange", onVisibilityChanged, false);
document.addEventListener("msvisibilitychange", onVisibilityChanged, false);