Skip to content

Commit

Permalink
feat: add Timer class to wrap timeout operations like resume or pause
Browse files Browse the repository at this point in the history
  • Loading branch information
achamorro-dev committed Feb 21, 2022
1 parent ba37e72 commit 89f817d
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ export { HttpError } from './http-client/http-error'
export { ExtendedError } from './extended-error/extended-error'
export type { Class } from './types/class'
export { range } from './range/range'
export { Timer } from './timer/timer'
44 changes: 44 additions & 0 deletions packages/utils/src/timer/timer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Timer } from './timer'

jest.useFakeTimers()

describe('Timer', () => {
it('should create a timer', () => {
let done = false

Timer.create(() => {
done = true
}, 1000)

jest.runAllTimers()
expect(done).toBe(true)
})

it('should create a timer and then stop it', () => {
let done = false

const timer = Timer.create(() => {
done = true
}, 1000)
timer.pause()
jest.runAllTimers()

expect(done).toBe(false)
})

it('should create a timer, stop it and resume it', () => {
let done = false

const timer = Timer.create(() => {
done = true
}, 1000)
jest.advanceTimersByTime(500)
timer.pause()
jest.advanceTimersByTime(1000)
expect(done).toBe(false)
timer.resume()
jest.advanceTimersByTime(500)

expect(done).toBe(true)
})
})
26 changes: 26 additions & 0 deletions packages/utils/src/timer/timer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export class Timer {
private timerId?: number | NodeJS.Timeout
private start?: Date
private remaining: number

constructor(private readonly callback: () => void, delay: number) {
this.remaining = delay
}

static create(callback: () => void, delay: number) {
const timer = new Timer(callback, delay)
timer.resume()
return timer
}

resume() {
this.start = new Date()
clearTimeout(this.timerId as NodeJS.Timeout)
this.timerId = setTimeout(this.callback, this.remaining)
}

pause() {
clearTimeout(this.timerId as NodeJS.Timeout)
this.remaining -= new Date().valueOf() - (this.start?.valueOf() ?? 0)
}
}

0 comments on commit 89f817d

Please sign in to comment.