Skip to content

Commit

Permalink
fix(useTimeout): clear setTimeout when component is unMounted
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 20, 2020
1 parent 079a6c8 commit 6a00858
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion 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)
Expand All @@ -18,6 +18,8 @@ export function useTimeout(delay = 1000, immediate = true) {
}
immediate && initTimeout()

getCurrentInstance() && onUnmounted(stop)

return {
ready,
start: () => initTimeout(),
Expand Down
9 changes: 9 additions & 0 deletions tests/useTimeout.test.ts
@@ -1,4 +1,5 @@
import { useTimeout } from '../src/useTimeout'
import invokeHook from './util/invokeHook'

beforeEach(() => {
jest.useFakeTimers()
Expand Down Expand Up @@ -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)
})

0 comments on commit 6a00858

Please sign in to comment.