鸿蒙harmonyOS 笔记:定时器

发布于:2025-03-25 ⋅ 阅读:(37) ⋅ 点赞:(0)

clearInterval

        clearInterval(number intervalID)

        取消由setInterval设置的定时器。

参数:

参数 类型 必填 描述
intervalID number 取消定时器的ID 。

示例:

clearInterval(111);

setInterval

        setInterval(function callback, number delay, any rest)

        设定一个定时器。

参数:

参数 类型 必填 描述
callback function 回调函数 。
delay number

执行回调函数的时间间隔,单位ms。

兼容数字的字符串,不传、传入非数字的字符串或其它类型,默认按0处理。

rest any param1, param2, ...等附加参数,它们会作为参数传递给回调函数。

示例: 

setInterval(() => {
  console.log('setInterval success');
}, 3000, 'param1', 'param2');

clearTimeout

        clearTimeout(number timeoutID)

        取消由 setTimeout 设置的定时器 。

参数:

参数 类型 必填 描述
timeoutID number 取消定时器的ID 。

示例:

clearTimeout(111);

setTimeout

        setTimeout(function callback, number delay, any rest)

        设定一个定时器。

参数:

参数 类型 必填 描述
callback function 回调函数 。
delay number

执行回调函数之间的时间间隔,单位ms。

兼容数字的字符串,不传、传入非数字的字符串或其它类型,默认按0处理。

rest any param1, param2, ...等附加参数,它们会作为参数传递给回调函数。

示例:

setTimeout(() => {
  console.log('setTimeout success');
}, 3000, 'param1', 'param2');

代码演示:

@Entry
@Component
struct LoginDemo {
  @State time: number = 0

  build() {
    Column() {
      this.titleBuilder()
      TextInput({ placeholder: '请输入手机号' })
        .backgroundColor(Color.White)
        .padding({ left: 0, top: 20, bottom: 20 })
        .placeholderColor('#ccc')
      Divider()
      Row() {
        TextInput({ placeholder: '请输入验证码' })
          .backgroundColor(Color.White)
          .padding({ left: 0, top: 20, bottom: 20 })
          .placeholderColor('#ccc')
          .layoutWeight(1)
        Text(this.time == 0 ? '发送验证码' : `${this.time}秒后获取`)
          .fontSize(14)
          .fontColor(Color.Gray)
          .onClick(() => {
            // 避免重复点击
            if (this.time != 0) {
              // return 会阻断后续代码执行
              return
            }
            // 延迟获取验证码
            setTimeout(() => {
              const code = Math.floor(1000 + Math.random() * 9000)
              // console.log('code:', code)
              AlertDialog.show({
                message: code.toString()
              })
            }, 2000)
            // 修改 倒计时时间
            this.time = 5
            const timeId = setInterval(() => {
              this.time--
              // 到了 0 关闭定时器
              if (this.time == 0) {
                clearInterval(timeId)
              }
            }, 1000)
          })
      }
      .width('100%')

      Divider()
      Button('登录')
        .width('100%')
        .type(ButtonType.Normal)
        .backgroundColor('#ea6051')
        .margin({ top: 50 })
    }
    .padding({ top: 80, left: 40, right: 40 })
    .width('100%')
    .alignItems(HorizontalAlign.Start)
  }

  @Builder
  titleBuilder() {
    Text('短信登录')
      .fontSize(25)
      .fontWeight(600)
      .margin({ bottom: 30 })
  }
}

效果展示: