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

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)
      }
},
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容