Skip to content

Commit

Permalink
feat(hooks/useDelay): add loop and introduce internal Timer class
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Oct 14, 2023
1 parent 7b315c7 commit 1f1dc69
Showing 1 changed file with 43 additions and 8 deletions.
51 changes: 43 additions & 8 deletions src/scripting/hooks/useDelay.ts
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 }
}

0 comments on commit 1f1dc69

Please sign in to comment.