Skip to content

Commit

Permalink
Merge branch 'feat-support-start'
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 26, 2020
2 parents f4b9f69 + 5376ed8 commit fb5821d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
10 changes: 8 additions & 2 deletions src/useInterval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ export function useInterval(fn: Function, delay: number, immediate = false) {
const clear = () => {
if (interval) {
clearInterval(interval)
interval = null
}
}
const start = () => {
if (!interval) {
interval = setInterval(fn, delay)
}
}
useLifecycles(
() => {
if (fn) {
immediate && fn()
interval = setInterval(fn, delay)
start()
}
},
() => {
clear()
}
)
return clear
return [clear, start]
}
22 changes: 20 additions & 2 deletions tests/useInterval.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,29 @@ test('should clearInterval when unmounted', () => {
})

test('interval should be cleared after invoking clear', () => {
let clear: () => void | undefined
let clear: () => void
invokeHook(() => {
clear = useInterval(callback!, 500)
[clear] = useInterval(callback!, 500)
})
clear!()
expect(clearInterval).toHaveBeenCalledTimes(1)
expect(clearInterval).toHaveBeenCalledWith(expect.any(Number))
})

test('interval will be start after invoking start', () => {
let clear: () => void
let start: () => void
invokeHook(() => {
const res = useInterval(callback!, 500)
clear = res[0]
start = res[1]
})
clear!()
expect(clearInterval).toHaveBeenCalledTimes(1)
expect(clearInterval).toHaveBeenCalledWith(expect.any(Number))
start()
expect(setInterval).toHaveBeenCalled()
expect(setInterval).toHaveBeenCalledWith(expect.any(Function), 500)
jest.advanceTimersByTime(500)
expect(callback).toHaveBeenCalled()
})

0 comments on commit fb5821d

Please sign in to comment.