手机锁屏js倒计时停止问题解决办法

环境:手机浏览器

1、visibilitychange  ios Safari 不兼容

重要的就是给window加一个visibilitychange监听,在里面判断document.visibilityState的值,如果为hidden,则是页面内容不可见时的钩子,如果不是hidden,则就是可见时的钩子,即唤醒页面或切换应用回到页面的回调。

vue里面使用方法可以参考以下代码

data:() =>{
  return {
    times:'',
    closeTime:''
  }
}
mounted() {
    window.addEventListener('visibilitychange',this.diffTime)
  },
  beforeDestroy(){
    window.removeEventListener('visibilitychange', this.diffTime)
  },
  methods: {
    // 处理锁屏时间差
    diffTime() {
      if (document.visibilityState =='hidden') {
       this.closeTime = Date.now()
      } else {
        this.times = this.times - (Date.now() - this.closeTime)/1000;
      }
    },
 }

 兼容性:ios不支持 

2、实时记录当前时间,比较时间差、(手机唤醒后会从新启动定时器)

部分示例代码:

<template>
    <i class="timer" v-text="msgs"></i>
</template>

<script>
export default {
  name: 'Timer',
  props: ['time'], 
  data () {
    return {
      msg: '',
      timer: null,
      myTime: 0,
      markTime: null
    }
  },
  components: {},
  mounted () {
    if (this.time) {
      this.myTime = this.time
      this.start()
    } else {
      this.msg = '00:00'
    }
  },
  destroyed () {
    clearTimeout(this.timer)
  },
  methods: {
    start () {
      let _this = this
      if (this.myTime === 0) {
        this.msg = '00:00'
        clearTimeout(this.timer)
        this.timer = null
        this.$emit('callback')
      } else {
        this.myTime--
        this.timer = setTimeout(() => {
      /*实现代码 start*/ let now = Date.now() if (_this.markTime) { // let d = (now - _this.markTime) / 1000 if (d > 2) { _this.myTime = _this.myTime - d } } _this.markTime = now
      /*end*/ this.start() }, 1000) } } }, } </script>

  

有更好处理方式请留言,互相学习!

原文地址:https://www.cnblogs.com/tengrl/p/10893115.html