[Vue] vue中setInterval的問題


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);
      })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM