您的当前位置:首页正文

小程序,列表多个定时器的实现

2024-11-13 来源:个人技术集锦

列表多个定时器的实现

本篇是taro框架下的小程序实现

// 数据
timeoutFlag: any = 0
timeoutList: any = []
hasBreak = 0
// 生命周期处理
componentDidHide() {
    this.timeoutFlag && clearTimeout(this.timeoutFlag);
}

componentWillUnmount() {
    this.timeoutFlag && clearTimeout(this.timeoutFlag);
}
//装载
this.timeoutList = []
this.timeoutFlag && clearTimeout(this.timeoutFlag);

this.timeoutList.push({ // 把未支付剩余时间加入倒计时队列
  index: index,
  time: item.expireMills,
  isEnd: false
});

if (this.timeoutList.length) {
  this.countDownNow(); // 运行倒计时
}
//倒计时结束
changeCancelStatus(index){
    if (index >= 0 && index < this.state.orderList.length) {
        this.state.orderList[index].dealState = 100
        this.state.orderList[index].dealStateMsg = '已取消'
    }
}

// 倒计时
countDownNow() {
  clearTimeout(this.timeoutFlag);
  this.timeoutFlag = setTimeout(() => {
    for (let i = 0; i < this.timeoutList.length; i++) {
      this.timeoutList[i].time -= 1000;
      if (this.timeoutList[i].isEnd) {
          break
      }
      if (this.timeoutList[i].time < 0) {
        this.hasBreak++
        this.changeCancelStatus(this.timeoutList[i].index)//
        this.timeoutList[i].isEnd = true
        this.forceUpdate()
      } else {
          this.formatTime(this.timeoutList[i]);
      }
    }

    if (this.hasBreak === this.timeoutList.length) {
      
    } else {
      this.countDownNow();
    }
  }, 1000);
  this.forceUpdate()
}

// 倒计时赋值
formatTime (timeObj) {
    this.state.leftTimeList[timeObj.index] = formatTimeString({
      time: timeObj.time
    });
}
// 时间格式化
function formatTimeString(op) {
  let nowOp = {
    ...op
  };

  let milliseconds = nowOp.time - (parseInt(nowOp.time / 1000, 10) * 1000);

  nowOp.time = (nowOp.time - milliseconds) / 1000; // 转为秒

  let seconds = nowOp.time - parseInt(nowOp.time / 60, 10) * 60;

  nowOp.time = (nowOp.time - seconds) / 60; // 转为分钟

  let minutes = nowOp.time - parseInt(nowOp.time / 60, 10) * 60;

  nowOp.time = (nowOp.time - minutes) / 60; // 转为小时

  let hour = nowOp.time - parseInt(nowOp.time / 24, 10) * 24;

  let day = (nowOp.time - hour) / 24;

  if (nowOp.completed) {
    let millisecondsLen = String(milliseconds).length;
    if (milliseconds < 3) {
      for (let i = 0; i < millisecondsLen; i++){
        milliseconds = '0' + milliseconds;
      }
    }
    seconds < 10 ? (seconds = '0' + seconds) : '';
    minutes < 10 ? (minutes = '0' + minutes) : '';
    hour < 10 ? (hour = '0' + hour) : '';
  }

  return {
    milliseconds,
    seconds,
    minutes,
    hour,
    day
  };
}

最后将timeList里面的时间展示在UI上面就可以了

显示全文