【HarmonyOS NEXT】实现登录获取验证码计数倒数

【需求】

  1. 点击获取验证码按钮开始倒计时,按钮倒计时结束前不可用
  2. 应用切后台要暂停倒数
  3. 应用切前台要继续倒数
  4. 登录页跳转到别的页面后,要结束倒数

【分析】

  1. 需要一个状态count记录倒数数值(默认值为 60),状态更新需要触发页面更新,此处使用@State修饰符
  2. 要现实倒数,需要定时器,可以使用setInterval,同时需要记录定时器 idtimerId
  3. 现实一个开始定时器的方法startTimer
  4. 现实一个暂停定时器的方法pauseTimer,因为setInterval,无法暂停,只能清除。要实现暂停效果,必须清除定时器,同时记录当前倒数数值,恢复定时器使用(本例因为切后台时count的值为当前倒数数值,直接使用即可),同时需要一个记录是否暂停的变量isPaused
  5. 现实一个恢复定时器的方法resumeTimer
  6. 离开当前页面需要取消定时器
  7. 销毁当前页面需要取消定时器

【代码】

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%')
  }
}

【效果图】

默认图 点击获取验证码 应用切后台 应用切前台
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值