JS常用工具函数-倒计时

博客指出倒计时是业务常见需求,着重提及了固定时间倒计时和指定结束时间倒计时这两种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

倒计时是业务中常见需求,写一下固定时间倒计时和指定结束时间倒计时

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>倒计时</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://lib.baomitu.com/vue/2.6.10/vue.min.js"></script>
</head>
<body>
  <div id="app">
    <div @click="countDown">{{codeText}}</div>
    <div :style="{color: isTimeCome&&'red'}" @click="runCutdown">{{endTimeText}}</div>
  </div>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          codeText: '发送验证码',
          seconds: 60,
          spaceTime: {
            day: '--',
            hour: '--',
            minute: '--',
            second: '--',
          },
          endTime: '2019-09-03', //自定义结束时间
          isTimeCome: false
        }
      },
      computed: {
        endTimeText(){
          return `${this.spaceTime.day}天${this.spaceTime.hour}时${this.spaceTime.minute}分${this.spaceTime.second}秒`
        }
       },
      methods: {
        // 一分钟倒计时
        countDown() {
          this.timer = setInterval(() => {
            this.codeText = `${this.seconds--}s后重发`
            if (this.seconds <= 0) {
              this.codeText = '重新发送'
              clearInterval(this.timer)
            }
          }, 1000)
        },
        // 指定结束时间倒计时
        cutdown(endTime, callback) {
          // 兼容safari
          if (endTime.includes('-')) {
            endTime = endTime.replace(/-/g, '/');
          }
          let currentTime = (new Date()).getTime();
          let deadline = (new Date(endTime)).getTime();
          let space = deadline - currentTime;
          space = space / 1000;
          // 时间结束的回调
          space < 0 && callback && callback();
          return space < 0
            ? {
              day: 0,
              hour: 0,
              minute: 0,
              second: 0
            }
            : {
              day: Math.floor(space / 60 / 60 / 24),
              hour: Math.floor(space / 60 / 60 % 24),
              minute: Math.floor(space / 60 % 60),
              second: Math.floor(space % 60)
            };
        },
        // 开始倒计时
        runCutdown() {
          this.endTimer = setInterval(() => {
            this.spaceTime = this.cutdown(this.endTime, () => {
              //倒计时为0时可触发操作
              this.isTimeCome = true
            });
          }, 1000);
        },
      }
    })
  </script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值