微信小程序驗證碼倒計時60秒提醒功能實現(xiàn)
問題
需求: 焙烤小程序有一個獲取短信驗證碼倒計時60秒再次獲取的功能。
遷移到登陸驗證碼獲取,需要有倒計時功能,app使用到setTimeout ,出問題了?!死活遞歸調(diào)用不了

image.png
實現(xiàn)
發(fā)現(xiàn)了setInterval倒計時,成功運行代碼如下
<!--index.wxml-->
<view class="container">
<view class="userinfo">
<button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 獲取頭像昵稱 </button>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<!--驗證碼按鈕 S-->
<view class="usermotto">
<button bindtap='sendSms' disabled='{{snsDisabled}}'>{{snsCodeMsg}}</button>
</view>
<!--驗證碼按鈕 E-->
</view>
//index.js
//獲取應用實例
const app = getApp()
Page({
data: {
snsCodeMsg: '獲取驗證碼',//默認字
snsMsgWait:60,//時間秒
snsDisabled:false,//是否可點擊
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件處理函數(shù)
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是網(wǎng)絡請求,可能會在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在沒有 open-type=getUserInfo 版本的兼容處理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
getUserInfo: function(e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
/**
* 驗證碼發(fā)送
*/
sendSms:function(){
// 60秒后重新獲取驗證碼
var inter = setInterval(function () {
this.setData({
snsCodeMsg: "重新發(fā)送(" + this.data.snsMsgWait + ")",
snsMsgWait: this.data.snsMsgWait - 1,
snsDisabled:true
});
if (this.data.snsMsgWait < 0) {
clearInterval(inter)
this.setData({
snsCodeMsg: "獲取驗證碼",
snsMsgWait: 60,
snsDisabled: false
});
}
}.bind(this), 1000);
//注意后面的bind綁定,最關(guān)鍵。不然又是未定義,無法使用外圍的變量
}
})
運行效果

image.png