这篇文章讲了用uniapp写定时器实现获取验证码倒计时功能应该怎么做?以及 需要注意哪些问题?
代码类别:vue3 uniapp setup js 小程序
用uniapp写定时器实现获取验证码倒计时功能应该怎么做?
可以按照以下步骤进行
1.在页面A 设置定时器变量,以及定时器时间
const countDown = ref(0);
const countDownTimer = ref(null);
2.开始倒计时
// 点击开始倒计时
const handleClick = () => {
countDown.value = 120;
startCountdownTimer();
}
// 开始倒计时
const startCountdownTimer = () => {
// 让countDownTimer永远只有1个
endCountDownTimer();
countDownTimer.value = setInterval(() => {
countDown.value -= 1
if (countDown.value == 0) {
endCountDownTimer();
}
}, 1000);
}
3.处理清除定时器的情况
// 清空计时器
const endCountDownTimer = () => {
clearInterval(countDownTimer.value);
countDownTimer.value = null;
}
// onHide 清除定时器,记录onHide的时间戳,详见⚠️注意点1
onHide(() => {
// 记录onHide时的时间戳
hideTimeStamp.value = moment().valueOf();
endCountDownTimer();
})
// onShow,如果之前正在倒计时,继续倒计时,祥见⚠️注意点3
onShow(() => {
if(countDown.value > 0 && hideTimeStamp.value){
const diffTime = moment().diff(hideTimeStamp.value, 'second');
if(countDown.value - diffTime > 0){
countDown.value = countDown.value - diffTime;
startCountdownTimer();
}else{
countDown.value = 0;
endCountDownTimer();
}
}
})
// onUnload 也需要清除定时器,详见⚠️注意点 2
onUnload(() => {
endCountDownTimer();
})
完整代码:vue3 setup版
import moment from "moment";
import {onHide, onShow, onUnload} from '@dcloudio/uni-app';
const hideTimeStamp = ref(null);
const countDown = ref(0);
const countDownTimer = ref(null);
// 点击开始倒计时
const handleClick = () => {
countDown.value = 120;
startCountdownTimer();
}
// 开始倒计时
const startCountdownTimer = () => {
// 让countDownTimer永远只有1个
endCountDownTimer();
countDownTimer.value = setInterval(() => {
countDown.value -= 1
if (countDown.value == 0) {
endCountDownTimer();
}
}, 1000);
}
// 清空计时器
const endCountDownTimer = () => {
clearInterval(countDownTimer.value);
countDownTimer.value = null;
}
// onHide 清除定时器,记录onHide的时间戳,详见⚠️注意点1
onHide(() => {
// 记录onHide时的时间戳
hideTimeStamp.value = moment().valueOf();
endCountDownTimer();
})
// onShow,如果之前正在倒计时,继续倒计时,祥见⚠️注意点3
onShow(() => {
if(countDown.value > 0 && hideTimeStamp.value){
const diffTime = moment().diff(hideTimeStamp.value, 'second');
if(countDown.value - diffTime > 0){
countDown.value = countDown.value - diffTime;
startCountdownTimer();
}else{
countDown.value = 0;
endCountDownTimer();
}
}
})
// onUnload 也需要清除定时器,详见⚠️注意点 2
onUnload(() => {
endCountDownTimer();
})
需要注意哪些问题?
- onHide的时候清除定时器,因为小程序的定时器是全局的,离开页面的时候需要回收,要不然会一直执行,因为离开页面A navigateTo 页面B 时,页面A会触发onHide,所以可以在onHide里清除定时器;
- onUnload 也需要清除定时器,要不然页面A navigateBack()之后没有清除定时器,定时器一直在执行,因为页面A navigateBack() 不会触发onHide,但是会触发onUnload,所以可以在onUnload里清除定时器。
- onShow的时候需要处理定时器,在倒计时页面A如果让小程序退到手机后台,又打开小程序,你会发现倒计时不动了,因为小程序退到手机后台触发了onHide,在onHide里清除了定时器,倒计时就不动了,而打开小程序的时候触发了页面的onShow,所以可以在里面接着处理倒计时