
回复
@Entry
@Component
struct TimerPage {
@State seconds: number = 0
@State isRunning: boolean = false
@State laps: string[] = []
private timerId: number = -1
// 时间格式化方法
private formatTime(sec: number): string {
const hours = Math.floor(sec / 3600)
const minutes = Math.floor((sec % 3600) / 60)
const seconds = sec % 60
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
// 定时器控制
private startTimer() {
this.timerId = setInterval(() => {
this.seconds += 1
}, 1000)
}
build() {
Column({ space: 20 }) {
// 时间显示
Text(this.formatTime(this.seconds))
.fontSize(40)
.fontColor(Color.Black)
// 控制按钮
Row({ space: 15 }) {
Button(this.isRunning ? '暂停' : '开始')
.width(100)
.onClick(() => {
if (this.isRunning) {
clearInterval(this.timerId)
} else {
this.startTimer()
}
this.isRunning = !this.isRunning
})
Button('重置')
.width(100)
.onClick(() => {
this.seconds = 0
this.laps = []
clearInterval(this.timerId)
this.isRunning = false
})
Button('记圈')
.width(100)
.onClick(() => {
this.laps = [...this.laps, this.formatTime(this.seconds)]
})
}
// 圈数记录
List({ space: 10 }) {
ForEach(this.laps, (item: string, index: number) => {
ListItem() {
Text(`第${index + 1}圈:${item}`)
.fontSize(16)
.margin(5)
}
})
}
.height('40%')
}
.width('100%')
.height('100%')
.padding(20)
}
// 清理定时器
aboutToDisappear() {
clearInterval(this.timerId)
}
}
基于ArkUI框架的计时器实现核心要点: