Skip to content

Commit 61db981

Browse files
committed
feat(hooks): add useTimeout hook
1 parent c245487 commit 61db981

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/__tests__/useTimeout.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { onMounted, onUnmounted } from 'vue-function-api';
2+
import { useTimeout } from '..';
3+
import renderHook from '../util/renderHook';
4+
5+
describe('useTimeout', () => {
6+
it('should be defined', () => {
7+
expect(useTimeout).toBeDefined();
8+
});
9+
10+
it('should return true after 3000ms', () => {
11+
const { vm } = renderHook<unknown>(() => {
12+
jest.useFakeTimers();
13+
const ready = useTimeout(3000);
14+
expect(ready.value).toBe(false);
15+
16+
onMounted(() => {
17+
expect(jest.getTimerCount()).toBe(1);
18+
jest.runOnlyPendingTimers();
19+
expect(ready.value).toBe(true);
20+
});
21+
22+
onUnmounted(() => {
23+
expect(jest.getTimerCount()).toBe(0);
24+
});
25+
});
26+
27+
vm.$destroy();
28+
});
29+
});

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export { default as useActions } from './useActions';
1414
export { default as useRouter } from './useRouter';
1515
export { default as useRef } from './useRef';
1616
export { default as useMountedState } from './useMountedState';
17+
export { default as useTimeout } from './useTimeout';
1718

1819
export default function install(Vue: VueConstructor) {
1920
Vue.mixin({ beforeCreate: setRuntimeVM });

src/useTimeout.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { value, onMounted, onUnmounted } from 'vue-function-api';
2+
3+
export default function useTimeout(delay = 0) {
4+
const ready = value(false);
5+
let timerId: number;
6+
7+
onMounted(() => {
8+
timerId = window.setTimeout(() => {
9+
ready.value = true;
10+
}, delay);
11+
});
12+
13+
onUnmounted(() => {
14+
window.clearTimeout(timerId);
15+
});
16+
17+
return ready;
18+
}

0 commit comments

Comments
 (0)