考试过程过程中,会有时间倒计时,当时间为零时,试卷要自动交卷,我开始的思路是把时间转成秒,之后通过setTimeout进行倒计时,
payCountdown(cm) {
//cm为秒钟
let _this = this;
if (cm >= 0 ) {
this.hour = Math.floor((cm / 1000 / 60 / 60) % 24);
this.hour =
this.hour.toString().length == 1 ? "0" + this.hour : this.hour;
this.minute = Math.floor((cm / 1000 / 60) % 60);
this.minute =
this.minute.toString().length == 1
? "0" + this.minute
: this.minute;
this.seconds = Math.floor((cm / 1000) % 60);
this.seconds =
this.seconds.toString().length == 1
? "0" + this.seconds
: this.seconds;
let _msThis = this;
//每过一秒就减一秒,进行倒计时
setTimeout(function () {
cm -= 1000;
_msThis.payCountdown(cm);
}, 1000);
}else {
_this.timeOver();
}
},
但是上边的方法有弊端,当浏览器不在该页面的时候,则会出现时间变慢,时间倒计时不对。
所以我就想着利用当前时间来进行倒计时,先让当前时间加上考试时间,之后用得到的时间减去当前时间。即使浏览器不在该页面,当回到这个页面,当前时间是变化的,所以倒计时的时间就是对的。
mounted() {
var time = new Date()//获得当前时间
var b = this.countdownTime //考试时间分钟
time.setMinutes(time.getMinutes() + b, time.getSeconds(), 0)//当前时间加上考试时间
this.timeDown(time)
},
//倒计时方法
timeDown(cm) {
const time = new Date();
//用得到的时间,减去当前时间
const cha = cm - time;
if(cha > 0) {
this.hour = Math.floor((cha / 1000 / 60 / 60) % 24);
this.hour =
this.hour.toString().length == 1 ? "0" + this.hour : this.hour;
this.minute = Math.floor((cha / 1000 / 60) % 60);
this.minute =
this.minute.toString().length == 1
? "0" + this.minute
: this.minute;
this.seconds = Math.floor((cha / 1000) % 60);
this.seconds =
this.seconds.toString().length == 1
? "0" + this.seconds
: this.seconds;
setTimeout( ()=> {
//每隔一秒就调用一次
this.timeDown(cm);
}, 1000);
}else {
this.timeOver()
}
}