第一版时有发版,使用的是第三方插件wxTimer,但是使用时需求不够满足并且功能不够完善有问题,所以进行第二版倒计时开发,没使用插件,下面时使用逻辑和代码
1.定义获取时间函数,并获取到后台传来的当前系统时间,并没有自动获取到手机时间,是因为担心每个人手机的时间不一样,但是考试结束时间一样,就通过后台来获取保持一致
2.需要用到两个时间,当前的时间和结束的时间,通过转换为当前国际标准时间,这里设置的公共方法
//转换时间为中国标准时间
const setTime = (startTime,endTime,curTime) =>{
let
current , //当前时间
startTime1 , //考试开始时间
endTime1 = ""; //考试结束时间
let cur = curTime.replace(/\-/g, "/") //获取当前时间
let start = startTime
let end = endTime
let start1 = start.replace(/\-/g, "/")
let end1 = end.replace(/\-/g, "/")
current = new Date(cur)
startTime1= new Date(start1)
endTime1= new Date(end1)
console.log(current)
//Tue Jun 08 2021 10:41:33 GMT+0800 (中国标准时间)
let obj={
currentTime:current,
endTime:endTime1,
startTime:startTime1
}
return obj
}
3.将转换后的值带入到倒计时方法中
let obj = setTime(wx.getStorageSync('startTime'), wx.getStorageSync('endTime'), res.data)
let {
currentTime
} = obj
let {
endTime
} = obj
let {
startTime
} = obj
//这里设置6分钟的倒计时,是为了以防中途退出,时间不准确,从新校验时间
setTimeout(function () {
that.getTime()
}, 1*60*1000);
if(!that.data.currentTime) {
this.setData({
currentTime: new Date(currentTime).getTime()
})
that.countDown(new Date(endTime).getTime())
} else{
this.setData({
currentTime: new Date(currentTime).getTime()
})
}
}
4.开始倒计时
//考试结束倒计时方法
countDown(endTime) {
let that = this
let surplus = ""
let timer = setInterval(function() {
let currentTime = that.data.currentTime
let mss = endTime - currentTime//先计算结束时间减去当前时间
currentTime = currentTime+ 1000
that.setData({
currentTime: currentTime
})
// let mss =10 //先计算结束时间减去当前时间
if(mss <=0){
let {saveStateOver} = that.data
//当saveStateOver不为false时,结束给出交卷提示并自动交卷
if(saveStateOver){
that.setData({
show1: true
})
}
//倒计时结束,清除定时器
clearTimeout(timer)
timer = null
setTimeout(function () {
that.setData({
show1: false
})
//倒计时到了触发交卷
that.onClose()
}, 5000);
}
//toString().length 下面方法适当时/分/秒为个位数时前面补0为00:00...显示效果更好
var days = parseInt(mss / (1000 * 60 * 60 * 24));
var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
if(hours.toString().length < 2){
hours = "0"+hours
}
var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
if(minutes.toString().length < 2){
minutes = "0"+minutes
}
var seconds =parseInt((mss % (1000 * 60)) / 1000);
if(seconds.toString().length < 2){
seconds = "0"+seconds
}
if( days ==0){
surplus =hours + ":" + minutes + ":" + seconds; //计算剩余时间
}else{
surplus =days + ":"+ hours + ":" + minutes + ":" + seconds; //计算剩余时间
}
//surplus将倒计时输出到页面
that.setData({
timesOver:surplus
})
//设置1s
}, 1000)
},
效果如图