小程序中按钮验证码倒计时
wxml文件
:
<view>
<button type="primary" bindtap="countdown" disabled="{{isDisabled}}">{{title}}</button>
</view>
<view>
<button type="primary" bindtap="countdown1" disabled="{{isDisabled}}">{{title}}</button>
</view>
js文件
data: {
title:"发送验证码", // 按钮中显示的字符
titleConst:"发送验证码", // 重置后的按钮中显示的字符
count:3, // 倒计时的秒数
countConst:3, // 重置后的倒计时的秒数
isDisabled:false // 按钮是否禁用
},
// setInterval中用箭头函数,保证this和外部一致
countdown: function(){
let count = this.data.count;
// 当count不为0开始倒计时,当count为0就关闭倒计时
// 设置定时器
var countdown = setInterval(() => {
if( count == 0 ){
this.setData({
title:this.data.titleConst,
count: this.data.countConst,
isDisabled:false
});
// 取消定时器
clearInterval(countdown);
} else {
this.setData({
title:count-- + "s后重试",
isDisabled:true
});
}
}, 1000);
},
// 用that保存this,防止在setInterval中this被替换
countdown1: function(){
let that = this;
let count = this.data.count;
// 当count不为0开始倒计时,当count为0就关闭倒计时
// 设置定时器
var countdown = setInterval(function(){
if( count == 0 ){
that.setData({
title:that.data.titleConst,
count: that.data.countConst,
isDisabled:false
});
// 取消定时器
clearInterval(countdown);
} else {
that.setData({
title:count-- + "s后重试",
isDisabled:true
});
}
}, 1000);
}