Skip to content

Commit

Permalink
feat: add off api
Browse files Browse the repository at this point in the history
  • Loading branch information
molvqingtai committed Dec 8, 2024
1 parent 588dad3 commit cfe75d7
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
73 changes: 72 additions & 1 deletion __tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('Test timer', () => {
expect(timer.status).toBe('stopped')
})
})
describe('Test event', () => {
describe('Test on event', () => {
let timer: Timer
beforeEach(() => {
timer = new Timer(() => 'foobar', {
Expand Down Expand Up @@ -92,6 +92,77 @@ describe('Test timer', () => {
})
})

describe('Test off event', () => {
let timer: Timer
beforeEach(() => {
timer = new Timer(() => 'foobar', {
limit: 3,
interval: 50
})
})

test('should not emit start event after off', async () => {
const callback = vi.fn()
timer.on('start', callback)
timer.off('start')
timer.start()
timer.stop()
expect(callback).not.toHaveBeenCalled()
})

test('should not emit pause event after off', async () => {
const callback = vi.fn()
timer.on('pause', callback)
timer.off('pause')
timer.start()
timer.pause()
timer.stop()
expect(callback).not.toHaveBeenCalled()
})

test('should not emit stop event after off', async () => {
const callback = vi.fn()
timer.on('stop', callback)
timer.off('stop')
timer.start()
timer.stop()
expect(callback).not.toHaveBeenCalled()
})

test('should not emit end event after off', async () => {
const callback = vi.fn()
timer.on('end', callback)
timer.off('end')
timer.start()
await vi.advanceTimersByTimeAsync(200)
timer.stop()
expect(callback).not.toHaveBeenCalled()
})

test('should not emit tick event after off', async () => {
const callback = vi.fn()
timer.on('tick', callback)
timer.off('tick')
timer.start()
await vi.advanceTimersByTimeAsync(100)
timer.stop()
expect(callback).not.toHaveBeenCalled()
})

test('should not emit error event after off', async () => {
const callback = vi.fn()
const timer = new Timer(() => {
throw new Error()
})
timer.on('error', callback)
timer.off('error')
timer.start()
await vi.advanceTimersByTimeAsync(200)
timer.stop()
expect(callback).not.toHaveBeenCalled()
})
})

describe('Test sync callback', () => {
test('should call callback 3 times', async () => {
const callback = vi.fn()
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export default class Timer {
this.eventHub.on(event, listener)
}

off<T extends keyof TimerListener>(event?: T | T[], listener?: TimerListener[T]) {
this.eventHub.off(event, listener)
}

start() {
if (this.status === 'stopped' || this.status === 'paused') {
if (this.limit > 0) {
Expand Down

0 comments on commit cfe75d7

Please sign in to comment.