diff options
author | Florian Dold <florian.dold@gmail.com> | 2017-06-05 02:00:03 +0200 |
---|---|---|
committer | Florian Dold <florian.dold@gmail.com> | 2017-06-05 02:00:03 +0200 |
commit | e95027f37712c37be243403a78ff6a327a83177e (patch) | |
tree | 9c06c552002af3b3a6ad3139d29ee9bf07c6b1f2 /src/timer.ts | |
parent | 49949de808154d360fd2e9383da2377b146b90e4 (diff) |
properly implement db resetting
Diffstat (limited to 'src/timer.ts')
-rw-r--r-- | src/timer.ts | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/timer.ts b/src/timer.ts index dd67dbd29..f19e975ac 100644 --- a/src/timer.ts +++ b/src/timer.ts @@ -75,3 +75,69 @@ export function every(delayMs: number, callback: () => void): TimerHandle { export function after(delayMs: number, callback: () => void): TimerHandle { return new TimeoutHandle(setInterval(callback, delayMs)); } + + +const nullTimerHandle = { + clear() { + } +}; + +/** + * Group of timers that can be destroyed at once. + */ +export class TimerGroup { + private stopped: boolean = false; + + private timerMap: { [index: number]: TimerHandle } = {}; + + private idGen = 1; + + stopCurrentAndFutureTimers() { + this.stopped = true; + for (const x in this.timerMap) { + if (!this.timerMap.hasOwnProperty(x)) { + continue; + } + this.timerMap[x].clear(); + delete this.timerMap[x]; + } + } + + after(delayMs: number, callback: () => void): TimerHandle { + if (this.stopped) { + console.warn("dropping timer since timer group is stopped"); + return nullTimerHandle; + } + const h = after(delayMs, callback); + let myId = this.idGen++; + this.timerMap[myId] = h; + + const tm = this.timerMap; + + return { + clear() { + h.clear(); + delete tm[myId]; + }, + }; + } + + every(delayMs: number, callback: () => void): TimerHandle { + if (this.stopped) { + console.warn("dropping timer since timer group is stopped"); + return nullTimerHandle; + } + const h = every(delayMs, callback); + let myId = this.idGen++; + this.timerMap[myId] = h; + + const tm = this.timerMap; + + return { + clear() { + h.clear(); + delete tm[myId]; + }, + }; + } +} |