vue2中定时器的使用与销毁

vue2中定时器的使用与销毁

问题描述: 项目开发过程中总会使用到定时器,此次遇到一个根据服务器时间定时自动去更新北京时间的问题。其中用到定时器,之前用传统的清除定时器的方法都是几个定时器需要几个组件实例去控制(增加内耗),然后再统一在beforeDestroy去清除,还是比较麻烦的。
解决方案:

  1. 通过$once事件,在定义完定时器的位置使用hook来监听beforeDestroy,当beforeDestroy触发时,销毁定时器。

实施代码:

mounted(){
	const timer1 = setInterval(this.setTime, 1000);
    const timer2 = setInterval(this.getServerTime, 10000);
    // 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
    this.$once("hook:beforeDestroy", () => {
      clearInterval(timer1);
      clearInterval(timer2);
    });
},
methods:{
  	async getServerTime() {
      // 获取服务器时间
      let res = await getCurrentTime();
      if (res.code == "0") {
        this.serverTime = new Date(res.result).getTime();
      } else {
        message.error("服务器时间未获取成功!");
      }
    },
    setTime() {
      this.serverTime += 1000;
      this.currentTime = moment(this.serverTime).format("YYYY-MM-DD HH:mm:ss");
    },
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值