js实现倒计时效果

2,434 阅读1分钟

最终要实现的效果是这样跳动的倒计时:

image.png

//将日期转换成毫秒数
  getCountDown() {
  //获取开始的时间转换成毫秒数 //注意如果格式是yyyy-mm-dd hh:mm:ss需要转换(因为ios的时间适配不一样所以要改成yyyy/mm/dd hh:mm:ss.replace(/-/g, '/')正则转换)
    const startTime: any = new Date(
      this.houseData.judicialSaleHouse.auctionTime.replace(/-/g, '/')
    ).getTime();
    //获取当前时间转换成毫秒数
    const nowTime: any = new Date().getTime();
    //计算毫秒差
    const timeLag = startTime - nowTime;
    if (timeLag > 0) {
    //将毫秒数进行分割计算天数
      this.day = parseInt((timeLag / (1000 * 60 * 60 * 24)).toString());
      //计算小时数
      this.hour = parseInt(
        ((timeLag % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString()
      );
      //计算分钟数
      this.minute = parseInt(
        ((timeLag % (1000 * 60 * 60)) / (1000 * 60)).toString()
      );
      //计算秒数
      this.second = parseInt(((timeLag % (1000 * 60)) / 1000).toString());
      this.countDown();
    }
  }
  // 跳动的倒计时
  countDown() {
    if (this.second - 1 < 0) {
      if (this.minute - 1 < 0) {
        if (this.hour - 1 < 0) {
          if (this.day - 1 < 0) {
            clearTimeout(this.timeId);
            return;
          } else {
            this.day--;
            this.hour = 23;
            this.minute = 59;
            this.second = 59;
          }
        } else {
          this.hour--;

          this.minute = 59;
          this.second = 59;
        }
      } else {
        this.minute--;
        this.second = 59;
      }
    } else {
      this.second--;
    }
    this.timeId = setTimeout(this.countDown, 1000);
  }
//记得在销毁页面的时候去除定时器
beforeDestroy() {
    clearTimeout(this.timeId);
  }