TextTimer组件使用计时功能时遇到的常见场景如下。
通过设置setInterval定时器,每隔很短的时间获取一次当前时间戳,计算当前到结束的差值可以得到当前剩余时间,实现计时效果。计时过程以及结束可以自行添加操作。
参考代码如下:
@Entry
@Component
struct Index {
@State timeNum: number = 60000; // 单位ms
@State timeEnd: number = 0;
timeId: number = -1;
build() {
Column({ space: 10 }) {
Text(`${Math.floor(this.timeNum / 1000)}.${this.timeNum / 10 % 100 < 10 ? 0 : ''}${Math.floor(this.timeNum / 10 %
100)}s`)
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold);
Button('开始计时')
.onClick(() => {
if (this.timeId === -1) { // 防止重复执行
this.timeEnd = Date.now() + this.timeNum; // 设置结束时间
this.timeId = setInterval(() => {
if (Date.now() < this.timeEnd) { // 当前时间未到结束时间
this.timeNum = this.timeEnd - Date.now(); // 获取计时剩余时间,单位ms
// 添加执行过程中的操作
console.info(`${this.timeNum}`);
} else {
clearInterval(this.timeId); // 停止计时器
this.timeId = -1;
// 添加执行结束的操作
this.timeNum = 0; // 到达结束时间,剩余时间0
console.info(`计时结束`);
}
}, 10);
}
});
Button('暂停计时')
.onClick(() => {
if (this.timeId !== -1) {
clearInterval(this.timeId);
this.timeId = -1;
}
});
Button('重置计时')
.onClick(() => {
if (this.timeId !== -1) {
clearInterval(this.timeId);
this.timeId = -1;
}
this.timeNum = 60000;
});
}
.height('100%')
.width('100%');
}
} 运行效果图如下:

// EntryAbility.ets下相关代码
// 进入前台时触发
onForeground(): void {
console.info('应用进入前台');
if (textTimerInfo.inProgress) {
textTimerInfo.textTimerController.start(); // 如果原本是计时状态,进入前台开始计时
}
}
// 进入后台时触发
onBackground(): void {
console.info('应用进入后台');
textTimerInfo.textTimerController.pause(); // 进入后台时停止计时
} // Page2.ets
class TextTimerInfo {
textTimerController: TextTimerController; // 计时器控制器
inProgress: boolean; // 计时器原本是否在计时
constructor(textTimerController: TextTimerController, inProgress: boolean) {
this.textTimerController = textTimerController;
this.inProgress = inProgress;
}
}
export const textTimerInfo: TextTimerInfo = new TextTimerInfo(new TextTimerController(), false); // 导出计时器的信息
@Entry
@Component
struct Page2 {
build() {
Column({ space: 10 }) {
TextTimer({ isCountDown: true, count: 30000, controller: textTimerInfo.textTimerController })
.format('mm:ss.SS')
.fontColor(Color.Black)
.fontSize(50);
Button('开始计时')
.onClick(() => {
textTimerInfo.textTimerController.start();
textTimerInfo.inProgress = true;
});
Button('暂停计时')
.onClick(() => {
textTimerInfo.textTimerController.pause();
textTimerInfo.inProgress = false;
});
}
.height('100%')
.width('100%');
}
} 运行效果图如下:
