vue中定时器setInterval如何使用
更新:2023-03-04 20:21:31
人气:566
来源:互联网转载
A+
今天小编给大家分享一下vue中定时器setInterval如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
声明
mouted() {
this.timer = setInterval(()=>{
// 要执行的函数
})
}销毁
destoryed() {
this.clearInterval(this.timer)
}看起来是很简单也没有什么,但是坑来了,实际项目中使用

addSetInterval() {
const that = this
this.positionTimer = setInterval(() => {
if (that.resultArr.length < that.times) {
clearInterval(that.positionTimer)
that.positionTimer = null
console.log(that.times)
} else {
// 分批部署基站
if (that.times < that.resultArr.length) {
that.deployBaseStation()
console.log('渲染数组的第' + that.times + '项')
}
that.times++
}
console.log(1111111111111)
}, 500)
},由于这里定义了定时器,箭头函数内部和外部的作用域不同了,要定义一个变量来使函数内部使用vue数据的时候指向不出错,
that 是指vue , this是指定时器 positionTimer
之前为了确认定时器已经停止了,在destory中和定时器中都输出了定时器的值,即 console.log(this.positionTimer),然而,上图

离开当前路由,再回到当前路由,之后控制台打印

然后不久之后就是

在请教了同学之后,她说可能跟我打印定时器也有关系,输出的时候调用了定时器,导致定时器关闭失败,我也是真的无奈了,一开始也没有定义额外的变量来确定this的指向,具体原因不明,总之,在不输出定时器,改加了额外的变量之后,定时器停止了
最终代码如下:
destroyed() {
clearInterval(this.positionTimer)// 清除定时器
this.positionTimer = null
// 离开路由之后断开websocket连接
this.webSocketOnClose()
this.websocketclose()
},
methods: {
// 添加定时器
addSetInterval() {
const that = this // 声明一个变量指向vue实例this,保证作用域一致
this.positionTimer = setInterval(() => {
if (that.resultArr.length < that.times) {
clearInterval(that.positionTimer)
that.positionTimer = null
console.log(that.times)
} else {
// 分批部署基站
if (that.times < that.resultArr.length) {
that.deployBaseStation()
console.log('渲染数组的第' + that.times + '项')
}
that.times++
}
console.log(1111111111111)
}, 500)
},
推荐的文章
PHP经验分享
- ● PHP批量对TCP服务端指定多个IP非阻塞检查在线状态
- ● python实现TCP服务端持续接收关机、重启指令并输出结果【系列三】
- ● PHP给TCP服务端发送指令【系列二】
- ● PHP判断TCP服务端是否在线【系列一】
- ● PHP判断远程文件是否存在
- ● LINUX下用PHP获取CPU型号、内存占用、硬盘占用等信息代码
- ● PHP代码用UDP方式远程唤醒电脑让计算机开机
- ● apache下php生成验证码图片不能显示
- ● PHP使用AES加密解密示例(无偏移)
- ● Pluginmysql_native_passwordreported:''mysql_native_password'isdeprecate问题








