清除定时器

311 阅读1分钟

clearInterval() 清除定时器

为什么要清除定时器?

  • 页面切换之后要是不清楚定时器的话,定时器会一直执行,所以在实例销毁之前要关闭定时器。
  mounted(){
      // 开启定时器(每秒调取接口,刷新数据)
      this.timer = setInterval(() => {
          // 定时器的操作
      }, 20000);
  },
  // 实例销毁之前关闭定时器
  beforeDestroy(){
      clearInterval(this.timer);
  }
  // 开启定时器(每秒调取接口,刷新数据)
  this.timer = setInterval(() => {
      this.getInviteMoney();
  }, 20000);
  // 实例销毁之前关闭定时器
  this.$once("hook:beforeDestroy", () => {
      clearInterval(this.timer);
  });