JS 倒计时应该什么时候给变量time赋值?

作者站长头像
站长
· 阅读数 11

现在的问题是,如果把time 放在verification函数体中赋值,那么不会实时更新,如果放在定时器中,直接都不赋值了

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <style>
      html {
          font-size: 1rem;
      }

      body {
          background: #E3E3E3;
      }

      .card {
          height: 136px;
          width: 430px;
          border-radius: 12px;
          background-color: #FFF0F1;
          margin: 30px auto 0;
          display: flex;
          justify-content: space-around;
          align-items: center;
      }

      .buttonInCard {
          width: 108px;
          height: 45px;
          border-radius: 0.5rem;
          font-size: 1.25rem;
          background-color: #F00;
          color: #ffffff;
          border: none;
          cursor: pointer;
      }

      .subT {
          font-size: 22px;
          width: 10rem;
          height: 2rem;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
      }
  </style>
</head>
<body>
<div id="app-vue"></div>
<script>
  const cardDataList = [
    {
      title: '杭州市通用5元券',
      subTitle: '杭味面馆非常好吃,太好吃了,相当不错,味道鲜美,特别划算,快快抢购,聚划算',
    },
    {
      title: '杭州市10元券',
      subTitle: '兰州拉面非常好吃'
    },
  ];


  const CardVue = {
    props: {
      data: Object,
    },
    data () {
      return {
        time: '',
        isCounting: false
      }
    },
    mounted () {
        this.verification()
    },
    computed: {
      isTimeEnd() {
        return this.time !== 0
      }
    },
    methods: {
      verification() {
        if (this.isCounting) {
          return;
        }
        /**
         * 1、获取商品购买截止时间和当前时间
         * 2、计算倒计时时间
         * 3、进入倒计时
         * 4、计时结束,清除定时器
         * @type {boolean}
         */
        const endTime = '2023/7/6, 13:35:00'
        const endTimeStamp = new Date(endTime).getTime()
        const currentTime = new Date().getTime()
        const diff = endTimeStamp - currentTime
        console.log(this.formatTime(diff));
        const timeRes = this.formatTime(diff)
        if (timeRes[0] + timeRes[1] + timeRes[2]) {
          this.isCounting = true;
          const times = setInterval(() => {
            if (timeRes[0] + timeRes[1] + timeRes[2] === '000000' || timeRes[2].includes('-')) {
              clearInterval(times);
              this.isCounting = false;
            }
          }, 1000);
        }
      },
      buy(delay) {
        new Promise((resolve, reject) => {
          const time = setTimeout(() => {
            resolve('抢购成功')
            clearTimeout(time)
          }, delay)
        }).then(res => {
          alert(res)
        })
      },
      formatTime (time) {
        let h = Math.floor(time / (1000 * 3600))
        let m = Math.floor((time - h * 3600000) / (1000 * 60))
        let s = Math.floor((time - m * 60000) / (1000))
        let arr = [h,m,s]
        arr.forEach((item, index) => {
          arr[index] = item.toString()
          if (item.toString().length < 2) {
            arr[index] = `0${item}`
          }
        })
        return arr
      }
    },
    template: `
      <div class="card">
      <div>
        <div style="font-size: 1.5rem"><strong>{{ data.title }}</strong></div>
        <div class="subT">{{ data.subTitle }}</div>
      </div>
      <div>
        <div style="width: 108px;height: 45px; text-align: center; line-height: 45px" v-if="isTimeEnd">
          {{ time }}
        </div>
        <button class="buttonInCard" v-else @click="buy(1000)"><strong>抢购</strong></button>
      </div>
      </div>
    `
  };

  const CardListVue = {
    components: {CardVue},
    data() {
      return {
        cardDataList,
      };
    },
    template: `
      <div>
      <cardVue v-for="cardData in cardDataList" :data="cardData"/>
      </div>
    `,
  }

  Vue.createApp(CardListVue).mount('#app-vue');
</script>
</body>
</html>
回复
1个回答
avatar
test
2024-07-01
verification() {
  if (this.isCounting) {
    return;
  }
  const endTime = '2023/7/6, 13:35:00'
  const endTimeStamp = new Date(endTime).getTime()
  const currentTime = new Date().getTime()
  let diff = endTimeStamp - currentTime
  console.log(this.formatTime(diff));
  let timeRes = this.formatTime(diff)
  if (timeRes[0] + timeRes[1] + timeRes[2]) {
    this.isCounting = true;
    const times = setInterval(() => {
      diff -= 1000; // 每秒减少1000毫秒
      timeRes = this.formatTime(diff);
      this.time = timeRes.join(':'); // 更新time的值
      if (timeRes[0] + timeRes[1] + timeRes[2] === '000000' || timeRes[2].includes('-')) {
        clearInterval(times);
        this.isCounting = false;
      }
    }, 1000);
  }
},
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容