*/
export class VaultTimer {
#f: () => any
- #isPaused: boolean = false
- #remaining: number
- #start: number
+ #end: PerformanceMark
+ #start: PerformanceMark
#ticker: number | NodeJS.Timeout
#timeout: number | NodeJS.Timeout
+ get #measureOptions (): PerformanceMeasureOptions { return { start: this.#start.startTime, end: this.#end.startTime } }
+ get #remaining (): PerformanceMeasure { return performance.measure('vault-timer-remaining', this.#measureOptions) }
+
constructor (f: () => any, t: number) {
- this.#f = f
- this.#remaining = t
- this.#start = performance.now()
+ this.#f = () => {
+ clearTimeout(this.#timeout)
+ clearInterval(this.#ticker)
+ f()
+ this.#f = () => void 0
+ }
+ this.#start = performance.mark('vault-timer-start')
+ this.#end = performance.mark('vault-timer-end', { startTime: performance.now() + t })
this.#ticker = setInterval(Function.prototype, 1000)
- this.#timeout = setTimeout(this.#f, this.#remaining)
+ this.#timeout = setTimeout(this.#f, this.#remaining.duration)
}
pause () {
- if (!this.#isPaused) {
+ this.#start = performance.mark('vault-timer-paused')
+ const remaining = this.#remaining.duration
+ if (remaining > 0) {
clearTimeout(this.#timeout)
clearInterval(this.#ticker)
- const elapsed = performance.now() - this.#start
- this.#remaining -= elapsed
- this.#isPaused = true
}
}
reset (t: number) {
clearTimeout(this.#timeout)
clearInterval(this.#ticker)
- this.#remaining = t
- this.#start = performance.now()
+ this.#start = performance.mark('vault-timer-start')
+ this.#end = performance.mark('vault-timer-end', { startTime: performance.now() + t })
this.#ticker = setInterval(Function.prototype, 1000)
- this.#timeout = setTimeout(this.#f, this.#remaining)
- this.#isPaused = false
+ this.#timeout = setTimeout(this.#f, this.#remaining.duration)
}
resume () {
- if (this.#isPaused) {
- this.#start = performance.now()
- this.#ticker = setInterval(Function.prototype, 1000)
- this.#timeout = setTimeout(this.#f, this.#remaining)
- this.#isPaused = false
+ const remaining = this.#remaining.duration
+ if (remaining > 0) {
+ this.#start = performance.mark('vault-timer-start')
+ this.#end = performance.mark('vault-timer-end', { startTime: performance.now() + remaining })
+ this.#timeout = setTimeout(this.#f, remaining)
}
}
}