vue中定時(shí)器setInterval的使用及說明
深坑
自己在項(xiàng)目中使用setInterval,由于不正確的使用,竟然導(dǎo)致了瀏覽器崩潰,項(xiàng)目停止,電腦死機(jī)…可怕之極,下面詳細(xì)寫一下關(guān)于定時(shí)器的用法及注意事項(xiàng)
聲明
mouted() {
this.timer = setInterval(()=>{
// 要執(zhí)行的函數(shù)
})
}
銷毀
destoryed() {
this.clearInterval(this.timer)
}
看起來是很簡(jiǎn)單也沒有什么,但是坑來了,實(shí)際項(xiàng)目中使用

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 + '項(xiàng)')
}
that.times++
}
console.log(1111111111111)
}, 500)
},
由于這里定義了定時(shí)器,箭頭函數(shù)內(nèi)部和外部的作用域不同了,要定義一個(gè)變量來使函數(shù)內(nèi)部使用vue數(shù)據(jù)的時(shí)候指向不出錯(cuò),
that 是指vue , this是指定時(shí)器 positionTimer
之前為了確認(rèn)定時(shí)器已經(jīng)停止了,在destory中和定時(shí)器中都輸出了定時(shí)器的值,即 console.log(this.positionTimer),然而,上圖

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

然后不久之后就是

WTF???
在請(qǐng)教了同學(xué)之后,她說可能跟我打印定時(shí)器也有關(guān)系,輸出的時(shí)候調(diào)用了定時(shí)器,導(dǎo)致定時(shí)器關(guān)閉失敗,我也是真的無奈了,一開始也沒有定義額外的變量來確定this的指向,具體原因不明,總之,在不輸出定時(shí)器,改加了額外的變量之后,定時(shí)器停止了
最終代碼如下:
destroyed() {
clearInterval(this.positionTimer)// 清除定時(shí)器
this.positionTimer = null
// 離開路由之后斷開websocket連接
this.webSocketOnClose()
this.websocketclose()
},
methods: {
// 添加定時(shí)器
addSetInterval() {
const that = this // 聲明一個(gè)變量指向vue實(shí)例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 + '項(xiàng)')
}
that.times++
}
console.log(1111111111111)
}, 500)
},
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
element-ui動(dòng)態(tài)添加表單項(xiàng)并實(shí)現(xiàn)事件觸發(fā)驗(yàn)證代碼示例
這篇文章主要給大家介紹了關(guān)于element-ui動(dòng)態(tài)添加表單項(xiàng)并實(shí)現(xiàn)事件觸發(fā)驗(yàn)證的相關(guān)資料,其實(shí)就是利用了vue的v-for循環(huán)渲染,通過添加數(shù)組實(shí)現(xiàn)動(dòng)態(tài)添加表單項(xiàng),需要的朋友可以參考下2023-12-12
使用vue實(shí)現(xiàn)pdf預(yù)覽功能的方法
許多朋友想要材料上傳之后點(diǎn)擊預(yù)覽實(shí)現(xiàn)在瀏覽器上預(yù)覽的效果,所以本文將給大家介紹如何使用vue實(shí)現(xiàn)pdf預(yù)覽功能,文中有實(shí)現(xiàn)代碼,有需要的朋友可以參考閱讀下2023-08-08
vue?el-date-picker?日期回顯后無法改變問題解決
這篇文章主要介紹了vue?el-date-picker?日期回顯后無法改變問題解決,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

