Created
April 30, 2018 12:58
-
-
Save ETNOL/5ae8737de55963d5e728acc815663157 to your computer and use it in GitHub Desktop.
Timed Function class
This file contains hidden or 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
| 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) | |
| }) | |
| }) |
This file contains hidden or 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
| 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