计时器:从零开始不断往上加,在特定条件下结束,一般用在游戏开始计时,游戏结束停止
1、在Html中放一个盒子,用于显示计时器上的时间,插值表达式ti实时显示时间
<!-- 计时器框 -->
<view class="Remember-Timer">
{{ ti }}
</view>
2、声明需要得所有变量
data() {
return {
ti: '00:00:00', //初始化显示时间
timer: '',
hour: 0, //小时
minute: 0, //分钟
seconds: 0, //秒钟
}
}
3、计时器方法
setInterval是一个实现定时调用的函数,可按照指定的周期(以毫秒计)来调用函数或计算表达式。setInterval方法会不停地调用函数,直到 clearInterval被调用或窗口被关闭。
begin() {
// 第一个参数是要执行的代码 第二个参数表示等待多长时间的毫秒数
this.timer = setInterval(this.startTimer, 1000);
},
// 开始计时
startTimer() {
//开始计时,秒+1
this.seconds += 1;
if (this.seconds >= 60) {
// 秒钟大小等于60时 秒钟清零 分钟加一
this.seconds = 0;
this.minute = this.minute + 1;
// console.log('分钟数',this.minute);
}
if (this.minute >= 60) {
// 分钟大小等于60时 分钟清零 小时加一
this.minute = 0;
this.hour = this.hour + 1;
}
// 三元表达式判断时、分、秒是否小于10,小于自动补零,不小于0原样显示
this.ti = (this.hour < 10 ? '0' + this.hour : this.hour) + ':' + (this.minute < 10 ? '0' + this.minute :
this.minute) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
},
4、什么时候结束定时器,就在那块得逻辑上加上clearInterval
clearInterval(this.timer);
5、想在哪里用定时器,就在哪里引入下面代码
this.begin()
定时器:设定具体时间,例如一小时两分钟,常用在倒数、倒记时
1、在Html中放一个盒子,用于显示计时器上的时间,插值表达式ti实时显示时间
<!-- 计时器框 -->
<div> {{ti}}</div>
2、声明需要得所有变量
data() {
return {
// 计时器
ti: '00:00:00', //显示时间
timer: '',
hour: 1, //小时
minute: 2, //分钟
seconds: 30, //秒钟
}
},
3、计时器方法
setInterval是一个实现定时调用的函数,可按照指定的周期(以毫秒计)来调用函数或计算表达式。setInterval方法会不停地调用函数,直到 clearInterval被调用或窗口被关闭。
begin() {
// 第一个参数是要执行的代码 第二个参数表示等待多长时间的毫秒数
this.timer = setInterval(this.startTimer, 1000);
},
// 开始计时
startTimer() {
//小时数不等于0 分钟数为0 秒数为0时候
if (this.hour !== 0 && this.minute === 0 && this.seconds === 0) {
//小时数-1 分钟数变为59 秒数变为59
this.hour -= 1;
this.minute = 59;
this.seconds = 59;
}
//小时数等于0 分钟数不为0 秒数为0时候
else if (this.hour === 0 && this.minute !== 0 && this.seconds ===0) {
//小时不变仍为0 分钟书-1 秒数为59
this.minute -= 1;
this.seconds = 59;
} else if (this.hour === 0 && this.minute === 0 && this.seconds ===0) {
this.seconds = 0
clearInterval(this.timer);
} else if (this.hour !== 0 && this.minute !== 0 && this.seconds ===0) {
this.minute -= 1;
this.seconds = 59;
// console.log(this.hour,this.minute,this.seconds);
} else {
this.seconds -= 1;
}
// 时分秒 小于10 自动补零
this.ti = (this.hour < 10 ? '0' + this.hour : this.hour) + ':' + (this.minute < 10 ? '0' + this.minute :
this.minute) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
},
4、结束定时器和开启定时器与上面的计时器相同
注意:正数计时器用的是微信小程序的写法,倒数定时器用的vue,div和view、挂载生命周期小程序使用onLoad()但是vue使用mounted()