H5用js倒计时 手机切换到后台倒计时暂停问题处理

2020-03-25  本文已影响0人  凤梨罐头过期了

H5在息屏或者切换到后台,在打开的时候,短信倒计时会从原来的值开始,修复这个问题需要用到 visibility属性
我用的是vue

window.addEventListener('popstate', this.goBack)
  document.addEventListener('visibilitychange', this.resetTime)
}
beforeDestroy() {
  window.removeEventListener('popstate', this.goBack)
  window.removeEventListener('visibilitychange', this.resetTime)
}
resetTime() {
if (document.hidden) {
  this.closeTIme = Date.now()
} else {
  this.countDown()
}
countDown() {
    this.showCount = true
      if (!this.timer) {
        this.count = TIME_COUNT
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.closeTime = ''
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      } else if (this.closeTime) {
        this.count =
          this.count - ((Date.now() - this.closeTime) / 1000).toFixed(0)
      }
},
上一篇 下一篇

猜你喜欢

热点阅读