常见的实现定时轮询的方式主要有setInterval,setTimeOut,这里我们使用性能较好的window. requestAnimationFrame。结合EventBus全站的定时任务都使用一个定时任务流,实现流程如下:

初始化EventBus

// main.js
Vue.prototype.$EventBus = new Vue()

app.vue全局定时流

借助requestAnimationFrame轮训触发,通过设置时间间隔达到自己想要的定时效果。然后通过EventBus发布定时触发任务。需要定时执行的只需监听这个任务即可。

<template>
...
</template>
<script>
export default {
    data () {
        return {
            time: 0, // 时间标志位
            interval: 10000, // 定时任务执行时间间隔
            timer: null
        }
    },
    methods: {
        intervalTimer () {
            let currTime = new Date().getTime()
            if(currTime - this.time > this.interval || this.time === 0) {
                this.$EventBus.$emit('timerAttach', {timer})
                this.time = new Date().getTime()
            }
            this.timer = requestAnimationFrame(this.intervalTimer) // 返回值是一个long整数,请求ID,是回调列表中唯一的标识,你可以传这个值给window.cancelAnimationFrame()以取消回调函数
        }
    },
    destroyed () {
        // 组件销毁,关闭定时执行
        cancelAnimationFrame(this.timer)
    },
    created() {
        // 开启定时任务
        this.intervalTimer()
        // 可以在任何你需要定时执行的地方都监听eventBus的timerAttach事件,比如我们的消息通知需要一直定时执行,所以我们加在app的created方法中。
        _this.$EventBus.$on('timerAttach', (time) => {
          getMessage(_this.$store.state.user.GRWX).then(res => {
            if (res.status === 200) {
              _this.$store.commit('UPDATE_MESSAGE', res.data)
            }
          }).catch(err => {
            console.log('error ' + err)
          })
        })
    }
}
</script>

由于全局只有一个定时器,不是很会影响主线程。
唯一不好的就是可能会有10几毫秒的延迟,RequestAnimateFrame是与屏幕刷新频率有关系的。
比较好的就是定时触发与实际的定时任务执行实现了完全的解耦。

Logo

前往低代码交流专区

更多推荐