在鴻蒙 ArkTS 開發中,定時器是實現動態效果和定時任務的重要工具。基于鴻蒙 API 12 及以上版本,ArkTS 提供了功能豐富的定時器 API,本文將帶你全面了解定時器的使用方法。
一、定時器常用 API 介紹
ArkTS 中的定時器主要分為一次性定時器(setTimeout)和周期性定時器(setInterval),它們都位于全局命名空間中,使用非常方便。
1. setTimeout - 一次性定時器
typescript
setTimeout(handler: Function, delay: number, ...args: any[]): number
- handler:定時器觸發時執行的回調函數
- delay:延遲時間(毫秒)
- args:傳遞給回調函數的參數
- 返回值:定時器 ID,用于取消定時器
2. setInterval - 周期性定時器
typescript
setInterval(handler: Function, delay: number, ...args: any[]): number
參數和返回值與 setTimeout 相同,區別在于 setInterval 會按指定間隔重復執行回調函數。
3. clearTimeout - 取消一次性定時器
typescript
clearTimeout(timeoutId: number): void
- timeoutId:setTimeout 返回的定時器 ID
4. clearInterval - 取消周期性定時器
typescript
clearInterval(intervalId: number): void
- intervalId:setInterval 返回的定時器 ID
二、定時器使用步驟
1. 創建定時器
typescript
// 創建一次性定時器,2秒后輸出"Hello World"
const timeoutId = setTimeout(() => {console.log("Hello World");
}, 2000);// 創建周期性定時器,每秒輸出當前時間
const intervalId = setInterval(() => {console.log(new Date().toLocaleTimeString());
}, 1000);
2. 傳遞參數
typescript
setTimeout((name: string, age: number) => {console.log(`My name is ${name}, I'm ${age} years old.`);
}, 1500, "Tom", 20);
3. 取消定時器
typescript
// 取消一次性定時器
clearTimeout(timeoutId);// 取消周期性定時器
clearInterval(intervalId);
三、代碼實戰與分析
下面通過幾個實際案例來深入理解定時器的使用。
案例 1:簡單倒計時功能
typescript
@Entry
@Component
struct CountdownTimer {@State count: number = 10;private timerId: number = -1;aboutToAppear() {// 啟動倒計時this.timerId = setInterval(() => {if (this.count > 0) {this.count--;} else {clearInterval(this.timerId);}}, 1000);}aboutToDisappear() {// 組件銷毀前取消定時器,避免內存泄漏clearInterval(this.timerId);}build() {Column() {Text(`倒計時: ${this.count}秒`).fontSize(30).fontWeight(FontWeight.Bold)}.width('100%').height('100%').justifyContent(FlexAlign.Center)}
}
代碼分析:
- 使用 @State 裝飾器實現數據綁定
- 在 aboutToAppear 生命周期函數中啟動定時器
- 每秒更新一次 count 值,當 count 為 0 時取消定時器
- 在 aboutToDisappear 生命周期函數中取消定時器,防止組件銷毀后定時器仍在運行
案例 2:實現輪播圖效果
typescript
@Entry
@Component
struct CarouselDemo {@State currentIndex: number = 0;private images: Array<string> = ['https://pic.photos/800/400?random=1','https://pic.photos/800/400?random=2','https://pic.photos/800/400?random=3','https://pic.photos/800/400?random=4'];private timerId: number = -1;aboutToAppear() {// 啟動輪播定時器this.timerId = setInterval(() => {this.currentIndex = (this.currentIndex + 1) % this.images.length;}, 3000);}aboutToDisappear() {// 組件銷毀前取消定時器clearInterval(this.timerId);}build() {Column() {// 輪播圖片Image(this.images[this.currentIndex]).width('100%').height(200).objectFit(ImageFit.Cover)// 指示點Row() {ForEach(this.images, (_, index) => {Circle().width(index === this.currentIndex ? 12 : 8).height(index === this.currentIndex ? 12 : 8).fill(index === this.currentIndex ? '#FF4500' : '#CCCCCC').margin({ left: 5, right: 5 })})}.margin(10).justifyContent(FlexAlign.Center)}.width('100%').height('100%')}
}
代碼分析:
- 使用數組存儲輪播圖片地址
- 定時器每 3 秒更新一次 currentIndex,實現圖片切換
- 通過 ForEach 動態生成指示點,當前圖片對應的指示點顯示為橙色
- 同樣注意在組件銷毀前取消定時器
四、注意事項
- 內存泄漏風險:如果組件銷毀前未取消定時器,定時器會繼續運行,可能導致內存泄漏。
- 性能考慮:過多或間隔過短的定時器會影響應用性能,特別是 setInterval,應謹慎使用。
掌握 ArkTS 中的定時器 API,能夠幫助你實現各種動態交互效果,如自動刷新、動畫過渡、數據輪詢等功能。合理使用定時器,并注意避免常見陷阱,將使你的應用更加流暢和穩定。