最近在写一个考试的h5页面时,有一个功能是考试时间限制,是一个倒计时的样式,直接上图:
考试时间不固定,根据后台返回的值来进行倒计时
<span class=""> <sm-icon name="alarm"></sm-icon> {{ time }}</span>
time = "";
timer = null;
remainingTime = 2000000; // 毫秒数
mounted() {
this.start();
}
/**
* @description: 倒计时
* @return {*}
*/
start() {
//
this.remainingTime = 1 * (60 * 60 * 1000) + 30 * (60 * 1000) + 0 * 1000;
const endTime = Date.now() + this.remainingTime;
this.timer = setInterval(() => {
const remainingTime = endTime - Date.now();
if (remainingTime <= 0) {
clearInterval(this.timer);
this.time = "00:00:00";
} else {
const hours = Math.floor(remainingTime / 3600000);
const minutes = Math.floor((remainingTime % 3600000) / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000);
this.time = `${this.formatTime(hours)}:${this.formatTime(minutes)}:${this.formatTime(
seconds,
)}`;
}
}, 1000);
}
stop() {
clearInterval(this.timer);
}
formatTime(time) {
return time < 10 ? `0${time}` : time;
}