vue中定時器setInterval的使用及說明
深坑
自己在項目中使用setInterval,由于不正確的使用,竟然導(dǎo)致了瀏覽器崩潰,項目停止,電腦死機…可怕之極,下面詳細(xì)寫一下關(guān)于定時器的用法及注意事項
聲明
mouted() {
this.timer = setInterval(()=>{
// 要執(zhí)行的函數(shù)
})
}
銷毀
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('渲染數(shù)組的第' + that.times + '項')
}
that.times++
}
console.log(1111111111111)
}, 500)
},
由于這里定義了定時器,箭頭函數(shù)內(nèi)部和外部的作用域不同了,要定義一個變量來使函數(shù)內(nèi)部使用vue數(shù)據(jù)的時候指向不出錯,
that 是指vue , this是指定時器 positionTimer
之前為了確認(rèn)定時器已經(jīng)停止了,在destory中和定時器中都輸出了定時器的值,即 console.log(this.positionTimer),然而,上圖

離開當(dāng)前路由,再回到當(dāng)前路由,之后控制臺打印

然后不久之后就是

WTF???
在請教了同學(xué)之后,她說可能跟我打印定時器也有關(guān)系,輸出的時候調(diào)用了定時器,導(dǎo)致定時器關(guān)閉失敗,我也是真的無奈了,一開始也沒有定義額外的變量來確定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('渲染數(shù)組的第' + that.times + '項')
}
that.times++
}
console.log(1111111111111)
}, 500)
},
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
element-ui動態(tài)添加表單項并實現(xiàn)事件觸發(fā)驗證代碼示例
這篇文章主要給大家介紹了關(guān)于element-ui動態(tài)添加表單項并實現(xiàn)事件觸發(fā)驗證的相關(guān)資料,其實就是利用了vue的v-for循環(huán)渲染,通過添加數(shù)組實現(xiàn)動態(tài)添加表單項,需要的朋友可以參考下2023-12-12
vue?el-date-picker?日期回顯后無法改變問題解決
這篇文章主要介紹了vue?el-date-picker?日期回顯后無法改變問題解決,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

