diff --git a/src/useTimeout.ts b/src/useTimeout.ts index 58db4d0..fd0f669 100644 --- a/src/useTimeout.ts +++ b/src/useTimeout.ts @@ -1,4 +1,4 @@ -import { ref } from 'vue' +import { getCurrentInstance, onUnmounted, ref } from 'vue' export function useTimeout(delay = 1000, immediate = true) { const ready = ref(false) @@ -18,6 +18,8 @@ export function useTimeout(delay = 1000, immediate = true) { } immediate && initTimeout() + getCurrentInstance() && onUnmounted(stop) + return { ready, start: () => initTimeout(), diff --git a/tests/useTimeout.test.ts b/tests/useTimeout.test.ts index 349b528..66810bd 100644 --- a/tests/useTimeout.test.ts +++ b/tests/useTimeout.test.ts @@ -1,4 +1,5 @@ import { useTimeout } from '../src/useTimeout' +import invokeHook from './util/invokeHook' beforeEach(() => { jest.useFakeTimers() @@ -39,3 +40,11 @@ test('setTimeout should be clear after calling stop', () => { stop() expect(clearTimeout).toHaveBeenCalledTimes(1) }) + +test('timeout should be clear when component is unmount', () => { + const wrapper = invokeHook(() => { + useTimeout(1000, true) + }) + wrapper.unmount() + expect(clearTimeout).toHaveBeenCalledTimes(1) +})