r-util-js/packages/common/src/timer/TimeoutTimer.ts

102 lines
2.3 KiB
TypeScript
Raw Normal View History

2026-03-16 17:58:57 +08:00
type TimerCallback = (time: number) => void;
export default class TimeoutTimer {
startTime = 0;
endTime = 0;
interval = 0;
time = 0;
id = -1;
stepEventListenerList = <TimerCallback[]>[];
countdownEventListenerList = <TimerCallback[]>[];
/**
*
* @param startTime
* @param endTime
* @param interval (ms)
*/
constructor(startTime = 5, endTime = 0, interval = 1000) {
this.startTime = startTime;
this.endTime = endTime;
this.interval = interval;
}
/**
*
* @param cb
* @returns
*/
addStepEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
return new TypeError("回调函数类型错误: cb: " + cb);
}
this.stepEventListenerList.push(cb);
}
/**
*
* @param cb
* @returns
*/
addCountdownEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
return new TypeError("回调函数类型错误: cb: " + cb);
}
this.countdownEventListenerList.push(cb);
}
/**
*
* @param startTime
* @param endTime
* @param interval
* @param stepEventListener
* @param countdownEventListener
* @returns
*/
static start(
startTime: number,
endTime: number = 0,
interval = 1000,
stepEventListener?: TimerCallback,
countdownEventListener?: TimerCallback,
) {
const timer = new TimeoutTimer(startTime, endTime, interval);
if (stepEventListener != null) {
timer.addStepEventListener(stepEventListener);
}
if (countdownEventListener != null) {
timer.addCountdownEventListener(countdownEventListener);
}
return timer;
}
/**
*
*/
start() {
this.time = this.startTime;
this.id = window.setInterval(() => {
this.time -= this.interval;
console.log(this.time);
this.stepEventListenerList.forEach((cb) => cb(this.time));
if (this.time <= this.endTime && this.id !== -1) {
this.stop();
}
}, this.interval);
}
/**
*
*/
stop() {
console.log("stop", this.id);
clearInterval(this.id);
this.id = -1;
this.time = this.endTime;
this.countdownEventListenerList.forEach((cb) => cb(this.time));
}
}