102 lines
2.3 KiB
TypeScript
102 lines
2.3 KiB
TypeScript
|
|
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));
|
||
|
|
}
|
||
|
|
}
|