-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(hooks/useDelay): add loop and introduce internal Timer class
- Loading branch information
1 parent
7b315c7
commit 1f1dc69
Showing
1 changed file
with
43 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 } | ||
} |