2025-10-31 18:29:53 +08:00
|
|
|
|
import {ITimer} from "./ITimer";
|
|
|
|
|
|
import {Time} from "../Time";
|
2025-06-07 20:32:43 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 私有类隐藏ITimer的实现
|
|
|
|
|
|
*/
|
2025-07-31 11:56:04 +08:00
|
|
|
|
export class Timer<TContext = unknown> implements ITimer<TContext>{
|
|
|
|
|
|
public context!: TContext;
|
2025-06-07 20:32:43 +08:00
|
|
|
|
public _timeInSeconds: number = 0;
|
|
|
|
|
|
public _repeats: boolean = false;
|
2025-07-31 11:56:04 +08:00
|
|
|
|
public _onTime!: (timer: ITimer<TContext>) => void;
|
2025-06-07 20:32:43 +08:00
|
|
|
|
public _isDone: boolean = false;
|
|
|
|
|
|
public _elapsedTime: number = 0;
|
|
|
|
|
|
|
|
|
|
|
|
public getContext<T>(): T {
|
2025-07-31 11:56:04 +08:00
|
|
|
|
return this.context as unknown as T;
|
2025-06-07 20:32:43 +08:00
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-10 13:12:14 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 定时器是否已完成
|
|
|
|
|
|
*/
|
|
|
|
|
|
public get isDone(): boolean {
|
|
|
|
|
|
return this._isDone;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 定时器已运行的时间
|
|
|
|
|
|
*/
|
|
|
|
|
|
public get elapsedTime(): number {
|
|
|
|
|
|
return this._elapsedTime;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
public reset(): void {
|
|
|
|
|
|
this._elapsedTime = 0;
|
|
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
public stop(): void {
|
|
|
|
|
|
this._isDone = true;
|
|
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
public tick(){
|
|
|
|
|
|
// 如果stop在tick之前被调用,那么isDone将为true,我们不应该再做任何事情
|
|
|
|
|
|
if (!this._isDone && this._elapsedTime > this._timeInSeconds){
|
|
|
|
|
|
this._elapsedTime -= this._timeInSeconds;
|
|
|
|
|
|
this._onTime(this);
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
if (!this._isDone && !this._repeats)
|
|
|
|
|
|
this._isDone = true;
|
|
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
this._elapsedTime += Time.deltaTime;
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
return this._isDone;
|
|
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-07-31 11:56:04 +08:00
|
|
|
|
public initialize(timeInsSeconds: number, repeats: boolean, context: TContext, onTime: (timer: ITimer<TContext>)=>void){
|
2025-06-07 20:32:43 +08:00
|
|
|
|
this._timeInSeconds = timeInsSeconds;
|
|
|
|
|
|
this._repeats = repeats;
|
|
|
|
|
|
this.context = context;
|
|
|
|
|
|
this._onTime = onTime.bind(context);
|
|
|
|
|
|
}
|
2020-08-26 19:56:48 +08:00
|
|
|
|
|
2025-06-07 20:32:43 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 空出对象引用,以便在js需要时GC可以清理它们的引用
|
|
|
|
|
|
*/
|
|
|
|
|
|
public unload(){
|
2025-07-31 11:56:04 +08:00
|
|
|
|
this.context = null as unknown as TContext;
|
|
|
|
|
|
this._onTime = null!;
|
2020-08-26 19:56:48 +08:00
|
|
|
|
}
|
2025-10-31 18:29:53 +08:00
|
|
|
|
}
|