Vue clear timer, delayer setIntederval, setTimeout optimization scheme:
There are two schemes to clear the timer. Scheme 1 is often used in the development process, and scheme 2 is recommended.
plan 1:
First define the timer name:
data() {
return {
timer: null // 定时器名称
}
},
Use timer:
this.timer = setTimeout(() => {
// 某些操作
}, 1000)
Finally, clear the timer during the beforeDestroy() life cycle:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
Scenario 2:
The method is to clear the timer by the position of the event listener $once after the timer is defined. Here is the code:
const timer = setInterval(() =>{
// 某些定时器操作
}, 500);
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
})