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() },