export default class Timer { static timers: { [key: string]: Timer; } = {}; timeout; handle: number | undefined; promise: Promise | false; resolve: Function; /** * Starts or restarts a named timer for the given time * @param {String} name Timer name * @param {Number} time The time to wait before finishing */ static async begin(name: string, time = 1000) { if (Timer.timers[name]) { return Timer.timers[name].reset(); } const instance = new Timer(time); instance.start(); Timer.timers[name] = instance; return instance; } constructor(timeout: number) { this.timeout = timeout; this.handle = undefined; this.promise = false; this.resolve = () => {}; } start() { this.promise = new Promise((r) => { this.resolve = r; }); this.handle = window.setTimeout(() => { this.resolve(true); }, this.timeout); return this.promise; } reset() { this.stop(); return this.start(); } stop() { this.resolve(false); clearTimeout(this.handle); } }