vue中setInterval停不下來,且越來越快,簡直和色狼一樣

vue中使用setInterval#


 

Copy

this.chatTimer = setInterval(() => { console.log(this.chatTimer); this.chatMsg(); }, 1000);

然後再組件銷燬前進行清除


 

Copy

beforeDestroy() { clearInterval(this.chatTimer); this.chatTimer = null; }

根據 setInterval 返回的 id 打印來看,請除定時器並沒有成功

但是這樣不行,定時器在局部更新的時候會多次賦值.更改了一種寫法,加了一重判斷之後依舊無法解決.


 

Copy

if (!this.chatTimer) { this.chatTimer = setInterval(() => { console.log(this.chatTimer); this.chatMsg(); }, 1000); }

解決#

使用全局變量


 

Copy

window.chatTimer = setInterval(() => { console.log(window.chatTimer); this.chatMsg(); }, 1000);


 

Copy

destroyed() { clearInterval(window.liaotianTimer); },

最終解決#


 

Copy

const chatTimer = setInterval(() => { console.log(chatTimer); this.chatMsg(); }, 1000); this.$once('hook:beforeDestroy', () => { clearInterval(chatTimer); })

分類: Vue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章