Timer problem in vue project

We all know that if you open a timer and don't close it, it will continue to execute, which is very performance-consuming, as shown in the figure below: Solution 1:
insert image description here
This
is also the method we usually use.
First define the timer name in the data function:

 data() {
    
    
    return {
    
    
      timer: null,
    };
  },

Then use the timer like this:

 this.timer = setInterval(() => {
    
    
      console.log(1);
    }, 100);

Finally clear the timer in the beforeDestroy() life cycle:

 beforeDestroy() {
    
    
    clearInterval(this.timer);
  },

There is absolutely no problem in writing this way, but when you use many timers in a page, you will find that it is a bit stuck, because the variable timer in data is stored in the component instance el , preferably only the lifecycle can access it if possible.
Also, when you write a lot, your beforeDestroy life cycle will become like this:


Then the readability of your code is very poor.
Solution 2:
This method is to clear the timer through the position of the $once event listener after the timer is defined. Here is the full code:

const timer = setInterval(() =>{
    
                        
    // 某些定时器操作                
}, 100);            
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {
    
                
    clearInterval(timer);                                    
})

Similar to other components that need to be used on the current page and need to be destroyed after leaving (such as components of some third-party libraries, etc.), this method can be used to solve the problem of running in the background after leaving.
In general, we recommend using option 2 to make the code more readable and clear at a glance.

Guess you like

Origin blog.csdn.net/pink_cz/article/details/126940048