From 1f1dc69c5f935cf3ca92243d4eb38df890b6b492 Mon Sep 17 00:00:00 2001 From: Lajos Meszaros Date: Sat, 14 Oct 2023 21:53:18 +0200 Subject: [PATCH] feat(hooks/useDelay): add loop and introduce internal Timer class --- src/scripting/hooks/useDelay.ts | 51 +++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/src/scripting/hooks/useDelay.ts b/src/scripting/hooks/useDelay.ts index ac77a9d6..39fb435a 100644 --- a/src/scripting/hooks/useDelay.ts +++ b/src/scripting/hooks/useDelay.ts @@ -1,27 +1,62 @@ let delayIdx = 0 +class Timer { + name: string = '' + delayOffsetInMs: number + /** + * Infinity or positive integer + */ + repetitions: number + isCancelled: boolean + + constructor(delayOffsetInMs: number, repetitions: number, isUnique: boolean = false) { + if (!isUnique) { + this.name = `delay${++delayIdx}` + } + + this.delayOffsetInMs = delayOffsetInMs + this.repetitions = repetitions + this.isCancelled = false + } + + toString() { + if (this.isCancelled) { + return `TIMER${this.name} off` + } else { + return `TIMER${this.name} -m ${this.repetitions === Infinity ? 0 : this.repetitions} ${this.delayOffsetInMs}` + } + } + + off() { + this.isCancelled = true + } +} + export const useDelay = () => { let delayOffset = 0 + const loop = (periodInMs: number, repetitions: number = Infinity) => { + return new Timer(periodInMs, repetitions) + } + /** - * creates a timer with a unique identifier + * creates a timer with a unique identifier (TIMERdelay16) + * can be cancelled */ const delay = (delayInMs: number = 0) => { delayOffset += Math.floor(delayInMs) - - return `TIMERdelay${++delayIdx} -m 1 ${delayOffset}` + return new Timer(delayOffset, 1) } /** - * creates a timer without any identification + * creates a timer without any identifier (TIMER) * so the delay stays unique at runtime - * and consequently being uncancellable with the off parameter + * and consequently being uncancellable with the off method */ const uniqueDelay = (delayInMs: number = 0) => { delayOffset += Math.floor(delayInMs) - - return `TIMER -m 1 ${delayOffset}` + return new Timer(delayOffset, 1, true) } - return { delay, uniqueDelay } + return { loop, delay, uniqueDelay } }