DEV Community

HarmonyOS
HarmonyOS

Posted on

How to create a timer with start, pause, and reset functions?

Read the original article:How to create a timer with start, pause, and reset functions?

Requirement Description

How to create a timer with start, pause, and reset functions?

Background Knowledge

The TextTimer component displays timing information and is controlled in text format. This component is supported since API version 8. Implements a controller for controlling the TextTimer component. A TextTimer component can only be bound to one controller, and the relevant commands can only be called after the component has been created.

Implementation Steps

1) Create the textTimerController and the timer format

2) Create a timer

3) Add play, pause, and reset images and functions.

Code Snippet / Configuration

  textTimerController: TextTimerController = new TextTimerController()
  @State format: string = 'mm:ss.SS'
Enter fullscreen mode Exit fullscreen mode
  @Builder
  Timer() {
    TextTimer({ isCountDown: false, controller: this.textTimerController })
      .format(this.format)
      .fontColor(Color.Gray)
      .margin({ top: 50, bottom: 10 })
      .fontSize(50)
      .onTimer((utc: number, elapsedTime: number) => {
        console.info('textTimer notCountDown utc is: ' + utc + ', elapsedTime: ' + elapsedTime)
      })
      .onAppear(() => {
        this.textTimerController.start()
      })
  }
Enter fullscreen mode Exit fullscreen mode
  build() {
    Flex({ justifyContent: FlexAlign.Center, wrap: FlexWrap.Wrap, alignItems: ItemAlign.Center }) {
      this.Timer()

      Row({ space: 20 }) {
        Image($r('app.media.play')).fillColor(Color.Gray).width('40').onClick(() => {
          this.textTimerController.start()
        })
        Image($r('app.media.pause')).fillColor(Color.Gray).width('40').onClick(() => {
          this.textTimerController.pause()
        })
        Image($r('app.media.reset')).fillColor(Color.Gray).width('40').onClick(() => {
          this.textTimerController.reset()
        })
      }
    }.backgroundColor(Color.Black).width('100%').height('100%')
  }
Enter fullscreen mode Exit fullscreen mode

Test Results

image.png

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-references/ts-basic-components-texttimer#start

Written by Merve Yonetci

Top comments (0)