vue專案中 正確的使用輪詢setInterval 請求介面
阿新 • • 發佈:2021-06-24
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() },