某些应用程序需要你持续关注。这类应用程序通常包括游戏、媒体播放器、任何 CPU/电池密集型的应用程序等等。对于这些类型的应用程序,当用户不再主动与您的应用程序交互时,做一些事情(以及用户友好的)可能很重要。

创建 init 函数。其中监听各种鼠标、键盘和触摸事件,来确保应用程序的活动状态。如果监听到这些事件中的任何一个,使用resetTimer 函数充当事件处理程序并被调用。

  • 使用 setTimeout 监听用户,一旦停止与应用程序交互,它就会开始计时。
  • 活跃时清除 timeoutID 定时器,并调用 goActive 函数。
  • 非活跃时重新计时,调用 goInactive 函数。
let timeoutID

function init() {
  this.addEventListener('mousemove', resetTimer)
  this.addEventListener('mousedown', resetTimer)
  this.addEventListener('keypress', resetTimer)
  this.addEventListener('DOMMouseScroll', resetTimer)
  this.addEventListener('mousewheel', resetTimer)
  this.addEventListener('touchmove', resetTimer)
  this.addEventListener('MSPointerMove', resetTimer)
  startTimer()
}

init()

function startTimer() {
  // 请等待2秒钟,然后再调用 goInactive
  timeoutID = setTimeout(goInactive, 2000)
}

function resetTimer(e) {
  clearTimeout(timeoutID)
  goActive()
}

function goInactive() {
  // do something
}

function goActive() {
  // do something
  startTimer()
}

查看效果