SoFunction
Updated on 2025-04-11

Solve the problem of the timer continuing to execute after vue component is destroyed

Directly upload the code, the following

(function(){
 if(this && !this._isDestroyed){ // Whether the _isDestroyed component is destroyed  return;
 }
  = "/serverMonitor?t="+ new Date().getTime();
},5000)

A very rough method, just check whether it is destroyed before execution.

The second method is to call the hook function beforeRouteLeave in the routing component.

beforeRouteLeave(to,from,next){
clearTimeout();
next();
}

Supplementary knowledge:The difference between created and mounted&& activated when vue is destroyed

I won't say much nonsense, let's just read the code~

// Close the current page will destroy the monitoring event (checkpay)destroyed() {
 clearInterval()
}
created()CreatingvueWhen the object,existhtmlTriggered before rendering;But pay attentioncreated()It will only trigger once; mounted()existhtmlIt will be executed after the rendering is completed;
 activated()进入当前存existactivated()Function page time,Triggered as soon as you enter the page;Can be used to initialize page data, etc.

The above article solves the problem of the timer continuing to execute after the vue component is destroyed. I hope it can give you a reference and I hope you can support me more.