vue 做H5单页面开发时,经常用到state状态管理,做定时器也是全局的。可能会在不用的页面里面对定时器进行关闭或重启的操作。
应用场景:比如预约会议,对会议室进行锁定2分钟的倒计时,加入在选择参会者页面停留,会议室锁定时间到期,弹出提示是否重新锁定,因此在此需要重新开启定时器 或者 清空定时器。
定时器的速度加快 是因为 setInterval 和 clearInterval没有一一对应,加入在不同.vue里面都对定时器进行clearInterval操作就会导致setInterval时 出现倍速的情况。个人场景代码如下
mutations.js
// 锁定会议室倒计时
timeDown (state) {
if(state.bookingMeeting.lockTimer !== null){//判断计时器是否为空
console.log('清空');
window.clearInterval(state.bookingMeeting.lockTimer);
state.bookingMeeting.lockTimer = '';
state.bookingMeeting.lockTimer = null;
}
state.bookingMeeting.lockTimer = setInterval(res => {
if (state.bookingMeeting.meetingRoomLockTime > 0) {
state.bookingMeeting.meetingRoomLockTime--;
}
}, 1000);
console.log(state.bookingMeeting.lockTimer);
}
.vue里面
watch: {
'$store.state.bookingMeeting.meetingRoomLockTime': function (news, olds) {
let that = this;
if (news !== olds) {
if (that.$store.state.bookingMeeting.meetingRoomLockTime <= 0 && that.$store.state.bookingMeeting.meetingRoomLockTime !== null && that.$store.state.bookingMeeting.meetingRoomLockTime !== 'null') {
that.$store.state.bookingMeeting.meetingRoomLockTime = 0;
console.log(that.$store.state.bookingMeeting.lockTimer);
console.log('关闭定时器');
if (that.$store.state.bookingMeeting.lockTimer) {
that.$messagebox({
title: '温馨提示',
message: '选中的会议已被释放,是否需要重新锁定?',
showCancelButton: true,
confirmButtonText: '重新锁定',
cancelButtonText: '取消'
}).then(action => {
console.log(action);
if (action === 'confirm') {
/* 导致倍速的bug的代码块
that.$store.state.bookingMeeting.lockTimer = null;
window.clearInterval(that.$store.state.bookingMeeting.lockTimer);
*/
// 锁定会议室
that.$store.dispatch('LockMeetingRoomAction').then(res => {
that.$store.commit('timeDown');
});
} else {
window.clearInterval(that.$store.state.bookingMeeting.lockTimer);
that.$store.state.bookingMeeting.lockTimer = null;
}
});
}
}
}
}
},
上面vue中使用监听是否倒计时到时 做出提示的功能,加入到时 就执行清空计时器 或者重启定时器
加入重启定时器 不能重复做clearInterval,否则会倍速定时器的bug
/* 导致倍速的bug的代码块 that.$store.state.bookingMeeting.lockTimer = null; window.clearInterval(that.$store.state.bookingMeeting.lockTimer);
*/
所以建议在重启定时器setInterval之前做clearInterval的操作即可避免倍速定时器的bug