Run setTimeout only when tab is active

前端 未结 6 1947
庸人自扰
庸人自扰 2020-11-29 20:57

Is there a way to stop setTimeout(\"myfunction()\",10000); from counting up when the page isn\'t active. For instance,

  1. A user arrives at a \"some
6条回答
  •  孤独总比滥情好
    2020-11-29 21:48

    (function() {
      var time = 10000,
          delta = 100,
          tid;
    
      tid = setInterval(function() {
        if ( document.hidden ) { return; }    
        time -= delta;
        if ( time <= 0 ) {
          clearInterval(tid);
          myFunction(); // time passed - do your work
        }        
      }, delta);
    })();
    

    Live demo: https://jsbin.com/xaxodaw/quiet


    Changelog:

    • June 9, 2019: I’ve switched to using document.hidden to detect when the page is not visible.

提交回复
热议问题