vue中定時器setInterval的使用及說明
深坑
自己在項目中使用setInterval,由于不正確的使用,竟然導致了瀏覽器崩潰,項目停止,電腦死機…可怕之極,下面詳細寫一下關于定時器的用法及注意事項
聲明
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
之前為了確認定時器已經(jīng)停止了,在destory中和定時器中都輸出了定時器的值,即 console.log(this.positionTimer),然而,上圖
離開當前路由,再回到當前路由,之后控制臺打印
然后不久之后就是
WTF???
在請教了同學之后,她說可能跟我打印定時器也有關系,輸出的時候調(diào)用了定時器,導致定時器關閉失敗,我也是真的無奈了,一開始也沒有定義額外的變量來確定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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
VUE3自定義指令防止重復點擊多次提交的實現(xiàn)方法
vue3項目,新增彈框連續(xù)點擊確定按鈕防止多次提交,在按鈕上添加自定義指令,這篇文章主要介紹了VUE3自定義指令防止重復點擊多次提交的實現(xiàn)方法,需要的朋友可以參考下2024-08-08Element InputNumber 計數(shù)器的實現(xiàn)示例
這篇文章主要介紹了Element InputNumber 計數(shù)器的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08解決element ui el-row el-col里面高度不一致問題
這篇文章主要介紹了解決element ui el-row el-col里面高度不一致問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08