倒计时函数

微信小程序中

/**
 * @that: this
 * @countdownKey: 倒计时的key
 * @timerKey: 定时器的key
 * @countdown: 倒计时的秒数,默认60
 * */

export function startCountdown(that, countdownKey, timerKey, countdown = 60){
  that.setData({
    [countdownKey]: countdown
  });
  const timer = setInterval(() => {
    const currentCount = that.data[countdownKey];
    if (currentCount <= 1) {
      clearInterval(that.data[timerKey]);
      that.setData({
        [countdownKey]: 0,
        [timerKey]: null
      });
    } else {
      that.setData({
        [countdownKey]: currentCount - 1
      });
    }
  }, 1000);
  that.setData({
    [timerKey]: timer
  });
}

用法:

  <view slot="button" class="text-primary" bindtap="getUnBindCode">{{unbindCodeCountdown > 0 ? unbindCodeCountdown + "s后重新获取" : "获取验证码"}}</view>
  data: {
    // 添加倒计时相关数据
    unbindCodeCountdown: 0, // 解绑验证码倒计时
    unbindCodeTimer: null, // 解绑验证码定时器
  },
  // 解绑手机号获取验证码
  getUnBindCode() {
      startCountdown(this, "unbindCodeCountdown", "unbindCodeTimer");
  },

在vue中

data:  return {
  // 获取验证码
      codeBtnTxt: '获取验证码',
      countIs: true,   //倒计时数是否完毕,
}

//倒计时
    _countDown(count) {
      let that = this
      if (count === 0) {
        this.codeBtnTxt = '重新获取'
        this.countIs = true
        return false;
      }
      this.codeBtnTxt = count + 'S'
      setTimeout(function () {
        count--;
        that._countDown(count);
      }, 900);
    },

用法:
this.countIs = false
this._countDown(60)
posted @ 2025-08-05 11:20  Teaism  阅读(8)  评论(0)    收藏  举报