目录
前言
我们在微信小程序实现短信验证码登录的时候,关闭定时器clearInterval的时候,会发现,第二次倒计时的时候 时间会变快一秒,依次变快
提示:以下是本篇文章正文内容,下面案例可供参考
一、在vue中的使用方法(小程序中无法使用)
微信小程序中对data数据赋值与vue中对与 不一样,vue中使用this.可直接赋值,
微信小程序中必须使用this.setData()方法才可
代码如下(示例):
<template>
<div class="test">
<span class="reGet" v-if="timeStatic">{{count}}s后重新发送</span>
<el-button class="get" @click="sendMsg" v-else>获取验证码</el-button>
</div>
</template>
<script>
export default {
name: 'test',
data(){
return{
timeStatic: false,
timer: '',
count: '',
}
},
methods:{
// 发送短信
sendMsg() {
// 调用发送短信接口,在接口成功回调中打开定时器
this.getCode()
},
// 短信倒计时
getCode() {
const TIME_COUNT = 60
if (!this.timer) {
this.count = TIME_COUNT
this.timeStatic = true
// this.sendMsg()
this.timer = setInterval(() => {
if (this.count > 1 && this.count <= TIME_COUNT) {
this.count--
} else {
// console.log(this.count)
this.timeStatic = false
clearInterval(this.timer)
this.timer = null
}
}, 1000)
}
},
}
}
</script>
二、微信小程序使用方法
错误方法:会导致定时器再次开启后时间越来越快
代码如下(示例):
getCode() {
that = this
const TIME_COUNT = 60
if (!this.data.timer) {
this.setData({
count: TIME_COUNT,
timeStatic: true
})
this.data.timer = setInterval(() => {
if (this.data.count > 1 && this.data.count <= TIME_COUNT) {
that.setData({
count: --this.data.count
})
} else {
that.setData({
timeStatic: false,
timer: null
})
clearInterval(this.data.timer)
}
}, 1000)
}
},
使用后发现定时器虽然停止了,但下一次点击会变成一次减2秒,这里是因为微信小程序无法在定时器内使用clearInterval(this.data.timer)
正确方法:所以我们需要用一个新的变量来接收定时器:
getCode() {
that = this
const TIME_COUNT = 60
if (!this.data.timer) {
this.setData({
count: TIME_COUNT,
timeStatic: true
})
// 此处将this.data.timer改为创建新变量let timer
let timer = setInterval(() => {
if (this.data.count > 1 && this.data.count <= TIME_COUNT) {
that.setData({
count: --this.data.count
})
} else {
that.setData({
timeStatic: false,
timer: null
})
// 此处关闭此定时器
clearInterval(timer)
}
}, 1000)
}
},
实现示例:
总结
以上为微信小程序使用定时器实现 发送短信60秒倒计时功能