setTimeout and setInterval Automatic Destruction Case in VUE

  • 2021-08-12 01:57:42
  • OfStack

In large single-page applications of Vue, there are often functions that require delayed execution (setTimeout) or interval heart (setInterval) under a certain route, but they must be cleaned up manually every time before the page destroy.

The normal code is as follows:


beforeDestroy() {
  this._timer && clearTimeout(this._timer);
}

But if 1 is not careful, it will forget and cause unexpected situations. Is there any way to avoid this situation?

Of course, that's the way to rewrite an setTimeout (or simply hijack window. setTimeout).


var _pageTimer = []; 
Vue.prototype.setTimeout = (fn, time) => {
  let handler = window.setTimeout(fn, time);
  _pageTimer.push(handler);
  
  return handler;
}

At the routing level, cleanup is performed every time the page changes:

router.beforeEach((to, from, next) = > { _pageTimer.map(handler = > { window.clearTimeout(handler); }) })

When the page is used again, call Vue's setTimeout, is this much more convenient? setInterval is also a sample.

The method is also suitable for ajax processing of page asynchronous request. By obtaining handler of ajax, the request can be canceled by calling handler. abort () when the section is switched, thus avoiding unnecessary pressure on server resources.

Additional knowledge: Using setTimeout in vue, the timer is not destroyed after exiting the page

Problem: The timer is still running when the page loops a method using setTimeout timing, or when the jump time between two pages is less than the time interval of the timer.

Reason: When we refresh the page, setTimeout and other timers created before the current page will be cleared, but just routing switching will not clear.


data (){
 return{
 clearTime: ''
 }
},
mounted () {
 randomGet () {
 //  In  1 Arrive in minutes  2 Between minutes   Irregular execution 
   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) //  Clear 
}

Related articles: