How to pause setTimeout when leaving the window with Javascript?

前端 未结 1 446
野性不改
野性不改 2021-01-27 01:52

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

相关标签:
1条回答
  • 2021-01-27 02:20

    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);
    
    0 讨论(0)
提交回复
热议问题