模拟业务逻辑
每一个小时需要手动打卡一次,打卡后重新计时,根据接口返回时间计算倒计时。根据接口返回时间戳对比上次打卡时间,展示剩余时间。
定义字段
data: {
BBtotalSeconds: 60 * 60, // 倒计时总秒数,60分钟转换为秒
BBtimerText: '60分00秒', // 显示的倒计时文本
BBtimer: null, // 定时器
currentTimestampInSeconds: 0, // 当前时间的时间戳(以秒为单位)
},
定义函数
updateTime(){
// 请求获取打卡状态
Http().then((resp) => { //模拟请求发送
if(resp.data.type == 2){ //打卡过
this.setData({ currentTimestampInSeconds:resp.data.time}) // 上次打卡时间
const currentTimeInSeconds = Math.floor(Date.now() / 1000); //当前时间
const timeDifferenceInSeconds =currentTimeInSeconds - resp.data.time ; //当前时间 - 打卡时间
if (timeDifferenceInSeconds > 3600) { // 60分钟等于3600秒
this.setData({BBtimerText: '已超时' });
} else {
this.resetTimer(3600- timeDifferenceInSeconds); // 如果没有超过60分钟,用剩余的时间继续倒计时
}
}else{ //没有打卡过
if(!this.data.currentTimestampInSeconds){
// 以秒为单位, 当前定时器开始时间
this.setData({currentTimestampInSeconds :Math.floor(Date.now() / 1000)})
this.startTimer(); //启动定时器
}
}
})
},
// 创建定时器
startTimer () {
let totalSeconds = this.data.BBtotalSeconds;
let that = this;
this.data.BBtimer = setInterval(()=> {
totalSeconds--;
if (totalSeconds < 0) {
clearInterval(that.data.BBtimer);
that.setData({
BBtimerText: '已超时'
});
} else {
let minutes =Math.floor(totalSeconds / 60);
let seconds =totalSeconds % 60;
let sum =`${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`
that.setData({
BBtimerText:sum
});
}
}, 1000); // 每秒更新一次
},
// 重置定时器
resetTimer(timeRemainingInSeconds) {
clearInterval(this.data.BBtimer); // 清除定时器
this.setData({
BBtotalSeconds: timeRemainingInSeconds // 设置剩余时间
});
this.startTimer(); // 重新启动定时器
},
初始化运行函数
onShow() {
this.updateTime()
}