js中定时器有两种,一个是循环执行setInterval,另一个是定时执行setTimeout
一、循环执行(setInterval)
顾名思义,循环执行就是设置一个时间间隔,每过一段时间都会执行一次这个方法,直到这个定时器被销毁掉
用法是setInterval(“方法名或方法”,“延时”), 第一个参数为方法名或者方法,注意为方法名的时候不要加括号,第二个参数为时间间隔
常见方法。在data中声明一个变量,定时器绑定到变量中,然后在beforeDestory中销毁这个定时器
举个例子:
方案一:
首先我在data函数里面进行定义定时器名称
<template>
<section>
<h1>hello world~</h1>
</section>
</template>
<script>
export default {
data() {
return {
timer: null // 定时器名称
};
},
mounted() { // 定时器一般写mounted() 生命周期内
this.timer = (() => {
// 某些操作
console.log(1);
}, 1000) // 1000毫秒
},
// 最后在beforeDestroy()生命周期内清除定时器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
};
&