The code is as follows:
data() { return { timer:null, //Timer name } }, created() { (); }, beforeDestroy(){ clearInterval();// Clear the timer = null; }, methods: { setTime(){ // Run the save method every minute = setInterval(()=>{ (); },60000) }, saveList(){ } }
The above writing function has been implemented, and closing the page will not continue to be executed. The page has not been stuck even after running for a long time.
Some people say that setInterval() is nested in setTimeout()
setinterval will not clear the timer queue. Every repeated execution will cause the timer to overlay and eventually jam your web page. The reason is related to JS engine threads (requires in-depth research on JS engine threads), but setTimeout comes with its own clear timer. I didn't have a page stuck so I didn't add setTimeout.
setInterval(() => { setTimeout(() => { () }, 0) }, 10000)
The difference between setInterval() and setTimeout():
One is to execute setInterval loop, and the other is to execute setTimeout regularly
1: setInterval loop execution, executed once every period of time, multiple times.
2: setTimeout executes after the time has arrived, only once.
Clear timer during beforeDestroy() life cycle
The timer needs to be cleared when the page is destroyed, otherwise it will always exist! !
Supplementary knowledge: timed execution (setTimeout)
Timed execution setTimeout is to set a time, and only execute once when the waiting time arrives, but the timer is still there after execution, but it is not running anymore;
grammar:
setTimeout(code, milliseconds, param1, param2, ...) setTimeout(function, milliseconds, param1, param2, ...) code/function Required。To call a code string,It can also be a function。 milliseconds Optional。Execute or call code/function Time to wait,In milliseconds。Default is 0。 param1, param2, ... Optional。 Other parameters passed to the execution function(IE9 This parameter is not supported by and earlier versions)。 Return value: Return one ID(number),Can make thisIDPass to clearTimeout() To cancel execution。 eg: Create a timer at the beginning setTimeout,Only in2Execute the method once in seconds。 let timer = setTimeout(() => { //Code that needs to be executed regularly ("Hello World"); }, 2000)
Summarize
This is the article about using a timer to run a certain method every few seconds for vue projects. For more related contents of vue timer running every few seconds, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!