vue中使用setInterval
this.chatTimer = setInterval(() => {
console.log(this.chatTimer);
this.chatMsg();
}, 1000);
然后再組件銷毀前進行清除
beforeDestroy() {
clearInterval(this.chatTimer);
this.chatTimer = null;
}
根據 setInterval 返回的 id 打印來看,請除定時器並沒有成功
但是這樣不行,定時器在局部更新的時候會多次賦值.更改了一種寫法,加了一重判斷之后依舊無法解決.
if (!this.chatTimer) {
this.chatTimer = setInterval(() => {
console.log(this.chatTimer);
this.chatMsg();
}, 1000);
}
解決
使用全局變量
window.chatTimer = setInterval(() => {
console.log(window.chatTimer);
this.chatMsg();
}, 1000);
destroyed() {
clearInterval(window.liaotianTimer);
},
最終解決
const chatTimer = setInterval(() => {
console.log(chatTimer);
this.chatMsg();
}, 1000);
this.$once('hook:beforeDestroy', () => {
clearInterval(chatTimer);
})