我们在移动端项目经常会碰到定时器的应用,在验证码获取,进入某个页面需要倒计时,或者进入页面开始计时,秒杀活动等,至于定时器的应用我今天就用这个比较简单的应用场景记录下。
首先我定义的一个对象,里面设置了三个属性并给出初始值,当点击发送时disabled会被设为true值,当还没有经过规定时间点击按钮时会return返回,否则执行发送任务;
sendCode(){
let that = this;
let data={
msgType:'set_passwd',
moblie:that.phone
}
// 请求接口
getCodeApi(data).then( res=> {
console.log(res);
setTimeout(function () {
that.$util.Tips({
title: res.msg
});
}, 1000);
/**
* 倒计时
*
*/
that.timer = setInterval(() => {
if (that.identifyObj.count >= 1) {
that.identifyObj.count--
// identifyObj.identifyText = '重新获取(' + identifyObj.count + '秒)'
that.identifyObj.identifyText = '重新获取'
that.identifyObj.disabled = true
} else {
that.identifyObj.count = 59
that.identifyObj.identifyText = '获取验证码'
that.identifyObj.disabled = false
clearInterval(that.timer)
}
}, 1000)
}).catch({
})
},
在倒计时过程中我们可以看到当倒计时未完成的时候disabled会一直为true,此时按钮点击无法请求接口发送验证码,当倒计时完成时重新赋值倒计时时间,disabled赋值为false,clearInterval取消由 setInterval() 函数设定的定时执行操作,这样就完成了此需求的操作编写。