vue項目中 正確的使用輪詢setInterval 請求接口


1.在data聲明 定時器為null; 

 注意 timer其實是個數字,代表着哪一個定時器。

  data() {
    return {// 輪循定時器
      timer: null
}

2.創建輪循器   

注意:先判斷是否存在已存在的定時器,有的話 關閉輪詢,再重新生成

 // 開啟輪詢  如果存在則先銷毀定時器后重新開啟
    createSetInterval(ids) {
      this.stopSetInterval()
      let _this = this
      this.timer = setInterval(() => {
        _this.checkListArrayPayState(ids)
      }, 5000)
    },
    // 關閉輪詢
    stopSetInterval() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }

3.關閉輪詢器

注意:當頁面離開的時候 定時器還是會存在在瀏覽器中,會繼續不斷請求接口 

所以不僅要手動關閉輪詢,也要在vue的銷毀生命周期里 再次檢查並關閉輪詢

 // 關閉輪詢
    stopSetInterval() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
// 離開頁面銷毀輪詢器
  destroyed() {
    this.stopSetInterval()
  },

 


免責聲明!

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



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