在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ clearInterval 清除定時器 有時候會無效?

clearInterval 清除定時器 有時候會無效?

  methods: {
    async init () {
      await this.getData();
      this.setTimer()
    },
    async getData() {
      //...ajax 獲取數據
    }
    async setTimer() {
      this.timer = setInterval(() => {
        this.oldItems = this.items;
        this.aniTimer ? clearTimeout(this.aniTimer) : "";
        if (this.token) {
          this.getData();
          console.log("頁面一刷新了");
        }
      }, 4000);
    }
  },
  async onShow() {
    this.init()
  },
  onHide() {
    clearInterval(this.timer);
    console.log("頁面一 結束刷新了");
  }

項目中幾個頁面都是通過Interval 每4秒更新數據,每次進入頁面都開始Interval,離開頁面都結束Interval。
但有時網速比較差時,跳轉到另一個頁面的后,控制臺還在不斷輸出"頁面一刷新了"?不知道是什么情況

----------------------------------------------------

第一個頁面執(zhí)行ajax都是使用同步的(耗時很長),還沒走到setInterval,就跳轉到另一個頁面,從第一個頁面離開執(zhí)行onHide時clearInterval(this.timer) this.timer還沒有設定,進入第二個頁面還是會執(zhí)行第一個頁面的定時器?這種情況有什么好的解決方法?

回答
編輯回答
檸檬藍

你到第二個頁面了,但擬第一個請求并沒有被取消. 所以當第一個請求結束時,繼續(xù)執(zhí)行了 this.setTimer().

解決方案:

async setTimer() {
  // 頁面已經隱藏了,不設置 timer.
  if (this._hide) return;

  this.timer = setInterval(() => {
      this.oldItems = this.items;
      this.aniTimer ? clearTimeout(this.aniTimer) : "";
      if (this.token) {
          this.getData();
          console.log("頁面一刷新了");
      }
  }, 4000);
}
onHide() {
 this._hide = true.
},
2017年5月23日 13:02
編輯回答
糖豆豆

沒用過mpvue

2017年3月17日 12:02
編輯回答
近義詞

這是vue嗎?
onShow和onHide什么時候調用的???

2017年7月31日 02:39