7、vue中使用定时器,setInterval setTimeout

博客介绍了Vue中有两套定时器,分别是windows对象的和Vue/Node.js封装的。默认使用Vue封装的定时器,但其只引用了setTimeout,clearInterval清不掉,建议手动引用windows对象的定时器,并在created定义,在beforeDestory中清除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue中两套定时器,一个是windows对象的,另一个是vue/node.js 封装的,需要引用

import { setInterval, clearInterval } from 'timers'

一般我们写

this.timer = setInterval(() => {
      this.getRealData()
}, 10000)

默认使用vue封装的,它会自动引用

import { setTimeout } from 'timers'

但是它只引用了一半,只引用了setTimeout  没有clearInterval 会出现清不掉的情况。所以还是自己手动引用比较好

建议使用windows对象的定时器,使用方法

window.clearInterval(this.timer)

定时器在created定义,在beforeDestory中清楚

created() {
    this.$nextTick(() => {
      this.getRealData()
      this.getDriver()
    })
    this.timer = setInterval(() => {
      this.getRealData()
    }, 10000)
}
beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer) // 关闭
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值