当前位置: 移动技术网 > IT编程>脚本编程>vue.js > VUE中setTimeout和setInterval自动销毁案例

VUE中setTimeout和setInterval自动销毁案例

2020年09月08日  | 移动技术网IT编程  | 我要评论
在vue的大型单页应用中,在某个路由下,经常会出现需要延迟执行(settimeout)或者间隔之心(setinterval)的函数,但是每次在页面destroy之前,都必须手动清理掉。正常代码如下:b

在vue的大型单页应用中,在某个路由下,经常会出现需要延迟执行(settimeout)或者间隔之心(setinterval)的函数,但是每次在页面destroy之前,都必须手动清理掉。

正常代码如下:

beforedestroy() {
  this._timer && cleartimeout(this._timer);
}

但是如果一不小心,就会忘记,会造成意想不到的情况,那么有什么办法能避免这种情况吗?

当然有,那就是重新写一个settimeout的方法(或者干脆劫持window.settimeout)。

var _pagetimer = []; 
vue.prototype.settimeout = (fn, time) => {
  let handler = window.settimeout(fn, time);
  _pagetimer.push(handler);
  
  return handler;
}

在路由层面,当每次页面变更时,执行清理工作:

router.beforeeach((to, from, next) => { _pagetimer.map(handler => { window.cleartimeout(handler); }) })

再页面使用时,调用vue的settimeout,这样是不是方便多了呢? setinterval也是一样的。

该方法还适用于对于页面异步请求的ajax处理,可以通过获取ajax的handler,在切面切换时,调用handler.abort() 取消请求,避免对服务器资源的不必要的压力。

补充知识:在vue中使用 settimeout ,退出页面后,计时器没有销毁

问题:页面在使用 settimeout 定时循环某方法,或者在两个页面之间跳转时间小于定时器的时间间隔时,定时器还在运行。

原因:当我们刷新页面时,会将当前页面之前创建的 settimeout 以及其他定时器都清除掉,但是仅仅是路由切换是不会清除的。

data (){
 return{
 cleartime: ''
 }
},
mounted () {
 randomget () {
 // 在 1分钟到 2分钟之间 不定时执行
   var r = math.random() * (2 - 1) + 1
   var t = math.ceil(r * 60000)
   // console.log(t)
   this.cleartime = settimeout(() => {
    this.submit()
    this.randomget()
   }, t)
  },
  submit () {
   console.log('aaaa')
  }
},
destroyed () {
 cleartimeout(this.cleartime) // 清除
}

以上这篇vue中settimeout和setinterval自动销毁案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网