記錄 - 在vue中使用setTimeout,離開當前路由setTimeout未銷燬的問題

問題:從第一個頁面跳轉到第二個頁面後,若是停留在第二個頁面,定時器還在運行。若是在兩個頁面之間來回跳轉,跳轉時間小於定時器的間隔時間時,也會出現重複建立setTimeout的狀況。this

緣由:當咱們刷新頁面時,會將當前頁面以前建立的setTimeout以及其餘定時器都清除掉,可是僅僅是路由切換是不會清除的。code

解決:具體代碼:`路由

data () {
    return {
      overtimer: null
    }
},
methods: {
    stoptime () {
      clearTimeout(this.overtimer);
    }
},
created () {
    this.overtimer = setTimeout(() => {
        this.$Message.error('讀取卡片超時');
     }, 10000)
    this.$once('hook:beforeDestroy', () => {            
      clearInterval(this.overtimer);
      this.overtimer = null;
    })
}

`定時器

相關文章
相關標籤/搜索