短信验证码, 试卷答题等倒计时函数的封装.

倒计时函数的封装

之前做的一个项目, 涉及到了答题的功能, 需要倒计时, 时间到了自动提交, 之前就自己随便写的一个方法, 获取到时间之后就开始倒计时, 但是细细想来觉得很有问题😮

最近做的一个项目, 登录需要短信验证码登录, 发送过验证码之后60s不能再次发送, 就想着把倒计时封装成一个构造函数, 这样以后需要倒计时的话就会比较方便.


废话不多说, 直接上代码!

function _countDown(thiz, timestamp) {
  timestamp = timestamp || new Date().getTime()

  var lasped = Math.floor((new Date().getTime() - timestamp) / 1000)
  var remain = Math.max(thiz._count - lasped, 0)

  thiz._callback && thiz._callback(remain)

  thiz._timer = remain > 0 ? setTimeout(function () {
    _countDown(thiz, timestamp)
  }, 1000) : null
}

var CountDown = function (count, callback) {
  this._count = parseInt(count) || 60

  if (callback && {}.toString.call(callback) === '[object Function]') {
    this._callback = callback
  }

  this._timer = null
}

CountDown.prototype.start = function () {
  if (!this._timer) {
    _countDown(this)
  }
}

CountDown.prototype.cancel = function () {
  if (this._timer) {
    clearTimeout(this._timer)
    this._timer = null
  }
}

module.exports = CountDown

使用方法也很简单😊:

  1. 在组件挂载后, 初始化倒计时函数;
  2. 分别传入对应的时间以及回调函数;
  3. 在对应的触发条件(点击发送验证码等…)触发时, 调用对应的start方法;
  4. 在结束条件(倒计时结束等…)触发时, 调用对应的cancel方法;

具体使用(伪代码):

data() {
  countDownCount: 60,  // 需要倒计时的时间 60s
  countDownModel: null,  // 实例
};
// 组件挂载
mounted() {
  // 初始化倒计时
  this.initCountDownModel();
},
methods: {
  // 初始化倒计时
  initCountDownModel() {
    const countDownModel = new CountDown(this.countDownCount, (cnt) => {
      if (cnt > 0) {
        // ...目前正在倒计时 ===> cnt 60 59 58...
      } else {
      	// 倒计时结束
        setTimeout(() => {
          // 关闭倒计时
          this.cancelCountDown();
        });
      }
    });
    this.countDownModel = countDownModel;
  },
  // 关闭倒计时
  cancelCountDown() {
    this.countDownModel.cancel();
  },
  /**
   * 开始倒计时, 具体情况, 调用时机不同
   * 短信验证码: 点击发送短信, 接口成功之后开始倒计时
   * 答题: 页面一开始就开始倒计时, 或者用户点击开始答题之后开始倒计时
   */
  startCountDown() {
    this.countDownModel.start();
  },

}

🎉🎉
还有待完善, 如果有不明白的, 欢迎大家一起讨论学习😊~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值