鸿蒙 回调函数

//新建Test.ets文件


interface CountdownCallback{

  onTick: (remaining: number) => void; // 显式标注参数类型

  onFinish: () => void;

}

export class Test {

  private intervalId: number = -1;

  private currentTime: number = 0;

  // 启动倒计时(带回调)

  start(duration: number, callback: CountdownCallback) {

    this.currentTime = duration;

    this.intervalId = setInterval(() => {

      this.currentTime--;

      callback.onTick(this.currentTime);

      if (this.currentTime <= 0) {

        this.stop();

        callback.onFinish();

      }

    }, 1000);

  }

  // 停止倒计时

  stop() {

    if (this.intervalId !== -1) {

      clearInterval(this.intervalId);

      this.intervalId = -1;

    }

}

}


//调用



import { Test } from '../model/Test';

@Entry

@ComponentV2

struct SplashScreen {

  @Local flag: boolean = true;

  private countdown: Test = new Test();

  @Local buttonText: string = ''

  build() {

    Stack() {

      if (this.flag) {

        Image($r('app.media.background'))

          .width('100%')

          .height('100%')

        Button('跳过======='+ this.buttonText)

      }

}

    .onAppear(() => {

      this.countdown.start(6, {

        onTick: (remaining) => {

          // 更新按钮文本

          this.buttonText = `${remaining}`;

        },

        onFinish: () => {

          this.flag = false;

        }

      });

    })

    .onDisAppear(() => {

      this.countdown.stop();

    })

  }

}
posted @ 2026-01-18 18:22  牛马米米  阅读(0)  评论(0)    收藏  举报