核心提示:前请提要通过短信码验证登录或身份信息,已成为当下众多应用中不可或缺的功能。但是,短信码不能获取太频繁,通常会有一个时间间隔的限制。需求实现虽然之前做过多次验证码倒计时的功能,但是都没能进行总结优化。这...
前请提要
通过短信码验证登录或身份信息,已成为当下众多应用中不可或缺的功能。但是,短信码不能获取太频繁,通常会有一个时间间隔的限制。
需求实现
虽然之前做过多次验证码倒计时的功能,但是都没能进行总结优化。这次终于逼迫自己认真重做一次,以便以后可以复用。
源码">源码
直接上完整的构造函数的源码。
// 验证码倒计时
var CountDown = function(options) {
// DOM节点
// 简单处理一下,只支持传 id 选择器;
if (typeof options === 'string') {
this.element = document.getElementById(options);
options = {};
} else {
if (typeof options.element === 'string') {
this.element = document.getElementById(options.element);
} else {
this.element = options.element;
}
}
// 触发事件类型
this.eventType = options.eventType || 'click'; //默认click事件触发
// 间隔时间
this.interval = options.interval || 60; //默认60s间隔
// 原有的文本
this.oldText = this.element.innerText;
// 开始
this.start = function() {
if (this.destroyed) {
return;
}
this.element.setAttribute('disabled', 'disabled');
this.timer = window.setInterval(function() {
if(!!this.interval) {
this.count();
} else {
this.end();
}
}.bind(this), 1000);
};
// 计算
this.count = function() {
this.element.innerText = '重新发送(' + this.interval + ')';
this.interval -= 1;
};
// 结束
this.end = function() {
if(!!this.timer) {
window.clearInterval(this.timer);
delete this.timer;
}
this._reset();
};
// 重置
this._reset = function() {
this.element.innerText = this.oldText;
this.element.removeAttribute('disabled');
this.interval = options.interval || 60;
};
// 绑定事件
this.element.addEventListener(this.eventType, this.start, false);
// 销毁
this.destroy = function() {
for (var name in this) {
if (this.hasOwnProperty(name)) {
delete this[name];
}
}
this.destroyed = true;
};
};
使用说明
start() 开始 end() 停止 destroy() 销毁根据实际业务场景,可以通过 start() 方法主动触发倒计时。同样根据实际使用情况,选择性调用 end() 和 destroy() 方法。
最简示例
var countDown = new CountDown('test');
初始化结束后,点击按钮即可开始倒计时。根据实际需求,可以调用 countDown.end() 提前主动停止。
自定义示例
初始化一个间隔时间为 120s 的计时器。
var countDown = new CountDown({
element: 'test',
interval: 120
});
总结
本文分享的是参考之前的应用业务,所设计的一个倒计时组件。虽然和最初比起来,已经优化过两次了,但是依旧有进一步改进的空间,适配更多的业务逻辑增强其通用性。


