Run setTimeout only when tab is active

前端 未结 6 1948
庸人自扰
庸人自扰 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条回答
  •  猫巷女王i
    2020-11-29 21:38

    What you'd have to do is set up a mechanism to set timeouts at small intervals, keeping track of total elapsed time. You'd also track "mouseenter" and "mouseleave" on the whole page (the or something). When the short-term timeouts expire, they can check the window state (in or out) and not restart the process when the window is not in focus. The "mouseenter" handler would start all paused timers.

    edit — @Šime Vidas has posted an excellent example.

提交回复
热议问题