The vue project uses a timer to run a method every few seconds

The code is as follows: 
data() { 
  return { 
    timer:null, //timer name 
  } 
}, 
created() { 
  this.setTime(); 
}, 
beforeDestroy(){ 
  clearInterval(this.timer); // clear the timer 
  this .timer = null; 
}, 
methods: { 
  setTime(){ 
  // Run the save method every minute 
      this.timer = setInterval(()=>{ 
        this.saveList(); 
      },60000) 
    }, 
    saveList() { 
    
    } 
}

The above writing has already realized the function, and closing the page will not continue to execute. The long-running page is not stuck.

Some people say that setInterval() is nested inside setTimeout()

setinterval will not clear the timer queue, each repeated execution will cause the timer to superimpose, and eventually your webpage will be stuck. The reason is related to the JS engine thread (need to study the JS engine thread in depth), but setTimeout has its own clear timer. I didn't have a page stuck, so I didn't add setTimeout.

        setInterval(() => {
            setTimeout(() => {
                this.queryChartTime()
            }, 0)
        }, 10000)

The difference between setInterval() and setTimeout():

One is to execute setInterval in a loop, and the other is to execute setTimeout regularly

1: setInterval is executed cyclically, once every other time, multiple times.

2: setTimeout is executed after the time is up, only once.

Clear the timer during the beforeDestroy() lifecycle

The timer needs to be cleared when the page is destroyed, otherwise it will always exist! !

Guess you like

Origin blog.csdn.net/wulikunbing/article/details/127746447