Skip to content Skip to sidebar Skip to footer

How To Pause Settimeout When Leaving The Window With Javascript?

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 does not sto

Solution 1:

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);

Post a Comment for "How To Pause Settimeout When Leaving The Window With Javascript?"