Skip to content

Instantly share code, notes, and snippets.

@ETNOL
Created April 30, 2018 12:58
Show Gist options
  • Select an option

  • Save ETNOL/5ae8737de55963d5e728acc815663157 to your computer and use it in GitHub Desktop.

Select an option

Save ETNOL/5ae8737de55963d5e728acc815663157 to your computer and use it in GitHub Desktop.
Timed Function class
import TimedFunction from '../TimedFunction'
describe('Timed Function', () => {
let func
let timedFunction: TimedFunction
beforeEach(() => {
func = jest.fn()
// speed this shit up
TimedFunction.tickRate = 100
})
it('exists', () => {
expect(typeof TimedFunction).toEqual('function')
})
// long running
it('calls its tick function every second after instantiation', (done) => {
func = jest.fn()
timedFunction = new TimedFunction(func, 10)
setTimeout(() => {
expect(timedFunction.timer).toBeGreaterThanOrEqual(2)
done()
}, 220)
})
it('calls the callback function after the timer has been hit', (done) => {
func = jest.fn()
timedFunction = new TimedFunction(func, 3)
expect(func).not.toBeCalled()
setTimeout(() => {
expect(func).toBeCalled()
done()
}, 320)
})
it('pauses the timer', (done) => {
func = jest.fn()
timedFunction = new TimedFunction(func, 3)
timedFunction.pause()
setTimeout(() => {
expect(func).not.toBeCalled()
done()
}, 320)
})
it('restarts the timer', (done) => {
func = jest.fn()
timedFunction = new TimedFunction(func, 3)
timedFunction.pause()
timedFunction.start()
setTimeout(() => {
expect(func).toBeCalled()
done()
}, 320)
})
})
export default class TimedFunction {
private static tickRate = 1000
timer = 0
interval: number | null = null
constructor(private func: Function, private callTime) {
this.start()
}
start(): void {
if (this.interval) {
return
}
// @ts-ignore Typing things setInterval returns a NodeJS instance but this is Browser instead
this.interval = setInterval(() => this.tick(), TimedFunction.tickRate)
}
pause(): void {
if (this.interval) {
clearInterval(this.interval)
}
this.interval = null
}
private tick(): void {
this.timer++
if (this.timer === this.callTime) {
this.func()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment