【需求】
- 点击获取验证码按钮开始倒计时,按钮倒计时结束前不可用
- 应用切后台要暂停倒数
- 应用切前台要继续倒数
- 登录页跳转到别的页面后,要结束倒数
【分析】
- 需要一个状态
count
记录倒数数值(默认值为 60),状态更新需要触发页面更新,此处使用@State
修饰符 - 要现实倒数,需要定时器,可以使用
setInterval
,同时需要记录定时器 idtimerId
- 现实一个开始定时器的方法
startTimer
- 现实一个暂停定时器的方法
pauseTimer
,因为setInterval
,无法暂停,只能清除。要实现暂停效果,必须清除定时器,同时记录当前倒数数值,恢复定时器使用(本例因为切后台时count
的值为当前倒数数值,直接使用即可),同时需要一个记录是否暂停的变量isPaused
- 现实一个恢复定时器的方法
resumeTimer
- 离开当前页面需要取消定时器
- 销毁当前页面需要取消定时器
【代码】
import { router } from '@kit.ArkUI'
const TOTAL_COUNT = 60
@Entry
@Component
struct LoginCountDown {
@State count: number = TOTAL_COUNT
timerId: number = -1
isPaused: boolean = false
isBack: boolean = false
onPageShow(): void {
!this.isBack && this.resumeTimer()
}
onPageHide(): void {
this.pauseTimer()
}
aboutToDisappear(): void {
clearInterval(this.timerId)
}
startTimer() {
this.timerId = setInterval(() => {
this.count--
this.isBack = false
if (this.count < 0) {
clearInterval(this.timerId)
this.count = TOTAL_COUNT
}
}, 1000)
}
pauseTimer() {
if (!this.isPaused) {
this.isPaused = true;
clearInterval(this.timerId)
}
}
resumeTimer() {
if (this.isPaused) {
this.isPaused = false
this.startTimer()
}
}
build() {
Row() {
Column({ space: 10 }) {
TextInput({ placeholder: '请输入手机号' })
.height(40)
Button(`获取验证码(${this.count}s)`)
.enabled(this.count === TOTAL_COUNT)
.width('100%')
.onClick(() => {
this.startTimer()
})
Button('跳页面')
.onClick(() => {
router.pushUrl({ url: 'pages/OtherDemo/KeyboardAvoidance' })
clearInterval(this.timerId)
this.isBack = true
this.isPaused = false
this.count = TOTAL_COUNT
})
}
.width('100%')
.padding(20)
}
.height('100%')
}
}
【效果图】