目前没有可以清理所有定时器的API,可以使用一个全局数组来存储所有定时器的ID,并在路由跳转、应用进入后台等场景时循环清除这些定时器。
@Entry @Component struct clearAllTimeouts1 { timeouts: number[] = []; @State content: number = 0; @State clickNum: number = 0; clearAllTimeouts(timeouts: number[]) { timeouts?.forEach(timeoutId => { clearTimeout(timeoutId); // 按照定时器ID循环清除定时器 }); this.timeouts = []; // 初始化数组 } onPageHide() { this.clearAllTimeouts(this.timeouts); // 离开页面时清除所有定时器 } build() { Row() { Column({ space: 20 }) { Button('create') .onClick(() => { this.clickNum++; let newTimeoutId = setTimeout(() => { this.content++; }, 2000); this.timeouts.push(newTimeoutId); }); Button('clear') .onClick(() => { this.clickNum = 0; this.content = 0; this.clearAllTimeouts(this.timeouts); // 主动触发清除所有定时器 }); Text('点击了' + this.clickNum + '次按钮'); Text('创建了' + this.content + '个定时器'); } .width('100%'); } .height('100%'); } }