SoFunction
Updated on 2025-04-12

vue beforeDestroy clearInterval ClearTimer failure solution

vue beforeDestroy clearInterval clear timer invalid

I found that there are quite a lot of people who have encountered this problem. I have encountered it myself and when I am modifying other people's code. Remember it quickly~ This method works very well.

scene

BeforeDestroy is triggered when the route jumps, and the relevant code for clearing the timer is also written in it, but it is still executing when it reaches other pages.

// Parent component A certain condition triggers a route jump, and the timer is always called in /xxx    ('/xxx')
// Subcomponents    mounted() {
      = setInterval(()=>{
        ();
      },5000);
    },
    beforeDestroy(){
      // Disconnect when the page leaves, clear the timer      ( '------------' );
      clearInterval();
    },

Solution

Using a programmatic event listener, try this:

mounted: function () {
  var timer = setInterval(()=>{
    ();
  },5000);
  // Listen to the timer via $once, and the beforeDestroy hook can be cleared.  this.$once('hook:beforeDestroy', () => {            
    clearInterval(timer);                                    
  })
}

Switch page clear timer in vue

Define global variables in data

intervalFlag: "",

Create a timer in mounted

Execute the loadTable method once every 5 minutes

  = setInterval(() => {
      ();
    }, 1000 * 5 * 60);

Clear timer in destroyed

  destroyed () {
    //Clear the scheduled tasks    if () {
      clearTimeout();
       = null;
    }
    var lastTimeoutId = setTimeout(";");
    for (var i = 0; i <= lastTimeoutId._id; i++) {
      clearTimeout(i);
    }
  },

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.