[Vue] vue中setInterval的問題

vue中使用setInterval

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

而後再組件銷燬前進行清除vue

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

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

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

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

解決

使用全局變量blog

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);
      })
相關文章
相關標籤/搜索