1. Temporizador de ejecución de bucle setInterval
La ejecución cíclica consiste en establecer un intervalo de tiempo, y este método se ejecutará cíclicamente cada vez hasta que se destruya el temporizador;
activador de página
mounted() {
this.getConsole()
/*
最初始情况,项目刚打开的时候,这个时候页面是必定没有定时器的,那么逻辑就会走else,这个时候就会注册一个定时器去循环调用相应逻辑代码
后续有三种情况
情况一:路由跳转,跳走了,就要清除这个定时器,所以在beforeDestroy钩子中要清除定时器
情况二:关闭项目,关闭项目了以后,系统就会自动停掉定时器,这个不用管它
情况三:刷新页面,这个时候vue组件的钩子是不会执行beforeDestroy和destroyed钩子的,所以
需要加上if判断一下,若还有定时器的话,就清除掉,所以这个就是mounted钩子的if判断的原因
*/
if (this.timer) {
clearInterval(this.timer);
} else {
this.timer = setInterval(this.getConsole, 1000);
}
},
methods: {
getConsole() {
console.log("定时器");
},
},
beforeDestroy() {
if(this.timer){
clearInterval(this.timer);
this.timer = null;
}
},
2. SetTimeout se ejecuta regularmente
La ejecución regular de setTimeout es establecer un tiempo, y solo se ejecuta una vez cuando llega el tiempo de espera , pero el temporizador sigue allí después de la ejecución, pero ya no se ejecuta;
De la siguiente manera: ejecute la función looper una vez después de esperar 2000 milisegundos.
<script>
export default {
data() {
return {
timer: '',
value: 0
};
},
methods: {
loop() {
this.value ++;
console.log(this.value);
}
},
mounted() {
this.timer = setTimeout(this.loop, 2000);
},
beforeDestroy() {
if(this.timer){
clearInterval(this.timer);
this.timer = null;
}
}
};
</script>