HarmonyOS为我们提供了基础的定时器能力——Timer (定时器)

这里介绍setInterval和clearInterval的使用

这里我们以累加为例,

点击【开始累加】按钮进行累加,实现每一秒加1的效果

代码:

@Entry
@Component
struct Index {
  @State num: number = 0
  @State x: number = 1

  build() {
    Column() {
      Row() {
      }.height(200)

      Text(`${this.num}`)
      Button('开始累加').onClick(() => {
        // 点击后每1秒加1
        setInterval(() => {
          this.num++
        }, 1000)
      })
    }
    .height('100%')
    .width('100%')
  }
}

在上述的基础上进行操作,进行点击【开始累加】后累加,以及点【停止】后停止累加,再次点击后【开始累加】后实现继续累加的效果

代码:

@Entry
@Component
struct Index {
  @State num: number = 0
  @State x: number = 1

  build() {
    Column() {
      Row() {
      }.height(200)

      Text(`${this.num}`)
      Button('开始累加').onClick(() => {
        // 点击后每1秒加1
        this.x = setInterval(() => {
          this.num++
        }, 1000)
      })
      Button('停止').onClick(() => {
        // 点击停止累加,再次点击【开始累加】按钮继续累加
        clearInterval(this.x)
      })
    }
    .height('100%')
    .width('100%')
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐