vue中定時器setInterval的使用及說明
深坑
自己在項目中使用setInterval,由于不正確的使用,竟然導致了瀏覽器崩潰,項目停止,電腦死機…可怕之極,下面詳細寫一下關于定時器的用法及注意事項
聲明
mouted() { this.timer = setInterval(()=>{ // 要執(zhí)行的函數 }) }
銷毀
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),然而,上圖
離開當前路由,再回到當前路由,之后控制臺打印
然后不久之后就是
WTF???
在請教了同學之后,她說可能跟我打印定時器也有關系,輸出的時候調用了定時器,導致定時器關閉失敗,我也是真的無奈了,一開始也沒有定義額外的變量來確定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) },
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決element ui el-row el-col里面高度不一致問題
這篇文章主要介紹了解決element ui el-row el-col里面高度不一致問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08