Files
oops-plugin-framework/assets/core/common/timer/Timer.ts
dgflash f2fe9d47b6 1. 存储模块全面优化,修复跨平台兼容性问题,完美支持所有Unicode字符
2. 存储模块性能提升,添加LRU缓存、批量操作支持,优化内存使用
3. 多语言模块性能与内存管理优化,组件查询性能提升
4. 时间模块类型安全与性能优化,使用泛型替代any,对象池机制减少内存分配
5. 事件系统修复双重注册、重复注册等严重问题,实现EventData对象池减少GC压力
6. RandomManager修复4个逻辑BUG,包括边界问题和越界问题
7. 音频模块内存与性能优化,避免重复加载,优化数据结构,添加完整清理机制
8. CCView与CCViewVM合并,支持按需启用MVVM
9. Collection模块优化,AsyncQueue添加队列容量限制,Collection查询性能提升
10. ECS系统全面优化,对象池复用减少内存分配,循环性能提升
11. 优化MVVM组件性能
2026-01-09 21:54:05 +08:00

111 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* @Author: dgflash
* @Date: 2023-01-19 11:09:38
* @LastEditors: dgflash
* @LastEditTime: 2023-01-19 14:28:05
*/
/**
* 定时触发组件
* @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037964&doc_id=2873565
* @example
export class Test extends Component {
// 创建一个定时跳动组件
private timer: Timer = new Timer(1);
update(dt: number) {
if (this.timer.update(this.dt)) {
console.log(每一秒触发一次);
}
}
}
*/
export class Timer {
callback: Function | null = null;
private _elapsedTime = 0;
get elapsedTime(): number {
return this._elapsedTime;
}
private _step = -1;
/** 触发间隔时间(秒) */
get step(): number {
return this._step;
}
set step(step: number) {
this._step = step; // 每次修改时间
this._elapsedTime = 0; // 逝去时间
}
get progress(): number {
// 添加零除数检查,避免 NaN
return this._step > 0 ? this._elapsedTime / this._step : 0;
}
/**
* 定时触发组件
* @param step 触发间隔时间(秒)
*/
constructor(step = 0) {
this.step = step;
}
/**
* 更新定时器
* @param dt 增量时间(秒)
* @returns 如果定时器触发返回 true否则返回 false
*/
update(dt: number): boolean {
// 快速返回,避免不必要的计算
if (this._step <= 0) return false;
this._elapsedTime += dt;
// 使用局部变量缓存,减少属性访问
const step = this._step;
if (this._elapsedTime >= step) {
// 修正时间累积误差:当累积时间远大于步长时,使用取模运算
// 避免长时间运行后的精度损失
if (this._elapsedTime >= step * 2) {
this._elapsedTime = this._elapsedTime % step;
}
else {
this._elapsedTime -= step;
}
// 优化回调调用,避免可选链和 call 的开销
if (this.callback) {
this.callback.call(this);
}
return true;
}
return false;
}
/**
* 重置定时器,清除已累积的时间
*/
reset(): void {
this._elapsedTime = 0;
}
/**
* 停止定时器
*/
stop(): void {
this._elapsedTime = 0;
this._step = -1;
}
/**
* 销毁定时器,释放内存
*/
destroy(): void {
this.callback = null;
this._elapsedTime = 0;
this._step = -1;
}
}