美文网首页前端开发
vue何时清除定时器

vue何时清除定时器

作者: 小程序前端超市 | 来源:发表于2020-04-21 11:26 被阅读0次

一、在组件销毁前

beforeDestroy() {
  // 清除定时任务
  clearTimeout(this.timer);
  this.timer = 0;
}

二、通过focus和blur事件

window.addEventListener('focus', () => {
  // 添加定时任务
});

window.addEventListener('blur', () => {
  // 清除定时任务
});

三、通过visibilitychange事件

document.addEventListener('visibilitychange', () => {
  if(document.hidden) { // 或用 document.visibilityState 来判断也行
    // 清除定时任务
  } else {
    // 添加定时任务
  }
});

四、非指定路由名称

if(this.$route.name === 'foo') {
  // 清除定时任务
  clearTimeout(this.timer);
  this.timer = 0;
}

写到最后,欢迎关注作者:http://www.techshare100.com/

相关文章

网友评论

    本文标题:vue何时清除定时器

    本文链接:https://www.haomeiwen.com/subject/msfuihtx.html