diff --git a/src/useInterval.ts b/src/useInterval.ts index 0ff48c6..17a1a6a 100644 --- a/src/useInterval.ts +++ b/src/useInterval.ts @@ -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] } diff --git a/tests/useInterval.test.ts b/tests/useInterval.test.ts index 5ce38b1..e37a3bf 100644 --- a/tests/useInterval.test.ts +++ b/tests/useInterval.test.ts @@ -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() +})