|
@@ -1,13 +1,10 @@
|
|
|
-export class Timer {
|
|
|
|
|
- private intervalHdl?: NodeJS.Timer;
|
|
|
|
|
- private subscribers: {
|
|
|
|
|
- [id: number]: {
|
|
|
|
|
- lastTick: number;
|
|
|
|
|
- seconds: number;
|
|
|
|
|
- tick: () => void;
|
|
|
|
|
- };
|
|
|
|
|
- } = {};
|
|
|
|
|
|
|
+type Subscriber = {
|
|
|
|
|
+ lastTick: number;
|
|
|
|
|
+ seconds: number;
|
|
|
|
|
+ tick: (() => void) | Promise<void>;
|
|
|
|
|
+};
|
|
|
|
|
|
|
|
|
|
+export class Timer {
|
|
|
private static INSTANCE?: Timer;
|
|
private static INSTANCE?: Timer;
|
|
|
public static get instance(): Timer {
|
|
public static get instance(): Timer {
|
|
|
if (!Timer.INSTANCE) {
|
|
if (!Timer.INSTANCE) {
|
|
@@ -16,6 +13,12 @@ export class Timer {
|
|
|
return Timer.INSTANCE;
|
|
return Timer.INSTANCE;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ private intervalHdl?: NodeJS.Timer;
|
|
|
|
|
+ private subscribers: {
|
|
|
|
|
+ [id: number]: Subscriber;
|
|
|
|
|
+ } = {};
|
|
|
|
|
+ private queue: Subscriber[] = [];
|
|
|
|
|
+
|
|
|
private constructor() {}
|
|
private constructor() {}
|
|
|
|
|
|
|
|
public start() {
|
|
public start() {
|
|
@@ -29,13 +32,26 @@ export class Timer {
|
|
|
const now = new Date();
|
|
const now = new Date();
|
|
|
Object.values(this.subscribers).forEach(sub => {
|
|
Object.values(this.subscribers).forEach(sub => {
|
|
|
if (now.getTime() >= sub.lastTick + sub.seconds * 1000) {
|
|
if (now.getTime() >= sub.lastTick + sub.seconds * 1000) {
|
|
|
- sub.lastTick = now.getTime();
|
|
|
|
|
- sub.tick();
|
|
|
|
|
|
|
+ this.queue.push(sub);
|
|
|
}
|
|
}
|
|
|
});
|
|
});
|
|
|
|
|
+ this.processQueue();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private async processQueue() {
|
|
|
|
|
+ while (this.queue.length > 0) {
|
|
|
|
|
+ const now = new Date();
|
|
|
|
|
+ const sub = this.queue.shift() as Subscriber;
|
|
|
|
|
+ sub.lastTick = now.getTime();
|
|
|
|
|
+ if (typeof sub.tick === 'function') {
|
|
|
|
|
+ sub.tick();
|
|
|
|
|
+ } else {
|
|
|
|
|
+ await sub.tick;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- public subscribe(seconds: number, tick: () => void) {
|
|
|
|
|
|
|
+ public subscribe(seconds: number, tick: (() => void) | Promise<void>) {
|
|
|
const lastTick = new Date().getTime();
|
|
const lastTick = new Date().getTime();
|
|
|
const id =
|
|
const id =
|
|
|
Object.keys(this.subscribers)
|
|
Object.keys(this.subscribers)
|