前端验证码倒计时算法
我看了很多算法的方式都是用settimeout函数来进行dom操作,在React,Vue或者小程序中不太适用,每次都去改代码也稍微有点麻烦,并且不是很难的算法.这里做个记录,方便以后查阅,该算法也进行了一些优化.按理说应该比网络上其他大部分算法好.至少看起来舒服.
接下来放源码了.
由于是React,Vue和小程序,所以和一般的算法不太一样.
首先是data数据.在React中是state,在Vue和小程序中是data.本文里的小程序,只是指微信小程序,由于支付宝和其他平台的没看过,估计也差不多.
- data或者state中的数据
{
countdown: 60,
btnDisabled: false,
text: '获取验证码',
}
- 接下来是主要算法:
countTime(second) {
let that = this;
let intervalTimer = setInterval(() => {
second -= 1;
if (second >= 0) {
// Vue中的写法
this.text = second + "s后重新获取";
this.btnDisabled = true;
// React的写法
that.setState({
text: second + "s后重新获取",
btnDisabled: true
});
// 小程序写法
that.setData({
text: second + "s后重新获取",
btnDisabled: true
});
} else {
clearInterval(intervalTimer);
// Vue中的写法
this.text = "获取验证码";
this.codeBtnDisabled = false;
// React的写法
that.setState({
text: "获取验证码",
btnDisabled: false
});
// 小程序写法
that.setData({
text: "获取验证码",
btnDisabled: false
});
}
}, 0x03e8);
}
好了,主要的算法就是这样.接下来只需要在发送验证码的按钮点击事件中调用
countTime 函数并传入参数就行.是60秒就传入60,120秒就传入120.
function countTime(second) {
var intervalTimer = setInterval(() => {
second -= 1;
if (second >= 0) {
btnSendCode.setAttribute("disabled", true);
btnSendCode.style.backgroundColor = "#DCDCDC";
btnSendCode.innerHTML = second + "s";
} else {
btnSendCode.removeAttribute("disabled");
btnSendCode.style.backgroundColor = "#d4143c";
btnSendCode.innerHTML = "获取验证码";
}
}, 0x03e8);
}