微信小程序页面实时倒计时

模拟业务逻辑

每一个小时需要手动打卡一次,打卡后重新计时,根据接口返回时间计算倒计时。根据接口返回时间戳对比上次打卡时间,展示剩余时间。

定义字段

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()
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值