倒计时函数的封装
之前做的一个项目, 涉及到了答题的功能, 需要倒计时, 时间到了自动提交, 之前就自己随便写的一个方法, 获取到时间之后就开始倒计时, 但是细细想来觉得很有问题😮
最近做的一个项目, 登录需要短信验证码登录, 发送过验证码之后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
使用方法也很简单😊:
- 在组件挂载后, 初始化倒计时函数;
- 分别传入对应的时间以及回调函数;
- 在对应的触发条件(点击发送验证码等…)触发时, 调用对应的
start
方法; - 在结束条件(倒计时结束等…)触发时, 调用对应的
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();
},
}
🎉🎉
还有待完善, 如果有不明白的, 欢迎大家一起讨论学习😊~