鸿蒙应用开发小例-计时器小工具

实现效果

实现思路

整个小工具放在一个自定义弹窗内,弹窗右上角是关闭按钮,中间显示格式化的计时时间,底部显示操作按钮,按钮根据状态切换开始和停止。

点击开始按钮,开始计时,按钮切换为停止按钮。

点击停止按钮,停止计时,按钮切换为开始按钮。

代码实现

以下只列出了核心代码,省略了无关的组件和样式等细节。

UI结构
Column() {
    Row() {
        Text(this.format(this.timeCount))
    }
    Row() {
        if (!this.isCounting) {
            Button() {
                Image($r('app.media.play'))
            }
            .onClick(() => {
                this.start()
            })
        } else {
            Button() {
                Image($r('app.media.stop'))
            }
            .onClick(() => {
                this.stop()
            })
        }
    }
}

timeCount:计时时间,通过format方法格式化。

isCounting:用于切换显示开始和停止按钮。

format方法中使用了dayjs库格式化时间。

  timer: number | null = null
  @State timeCount: number = 0
  @State isCounting: boolean = false
  stop = () => {
    clearInterval(this.timer)
    this.isCounting = false
  }
  start = () => {
    this.stop()
    this.timeCount = 0
    this.isCounting = true
    this.timer = setInterval(function () {
      if (!this.isCounting) clearInterval(this.timer)
      this.timeCount++
    }.bind(this), 1)
  }
  format = (count): string => {
    return dayjs(count).format('mm:ss:SSS')
  }

至此,一个简单的计时器就做好了。

想起了高中时候,比着看谁停的离1秒最近。

完结散花

如发现文章内容有任何问题,请提出您的宝贵意见予以指正,感谢您的阅读。

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值