提交 | 用户 | age
|
b49950
|
1 |
import { ref, watch } from 'vue'; |
V |
2 |
import { tryOnUnmounted } from '/@/utils/helper/vueHelper'; |
|
3 |
|
|
4 |
import { isFunction } from '/@/utils/is'; |
|
5 |
|
|
6 |
export function useTimeoutFn(handle: Fn<any>, wait: number) { |
|
7 |
if (!isFunction(handle)) { |
|
8 |
throw new Error('handle is not Function!'); |
|
9 |
} |
|
10 |
|
|
11 |
const { readyRef, stop, start } = useTimeoutRef(wait); |
|
12 |
|
|
13 |
watch( |
|
14 |
readyRef, |
|
15 |
(maturity) => { |
|
16 |
maturity && handle(); |
|
17 |
}, |
|
18 |
{ immediate: false } |
|
19 |
); |
|
20 |
return { readyRef, stop, start }; |
|
21 |
} |
|
22 |
|
|
23 |
export function useTimeoutRef(wait: number) { |
|
24 |
const readyRef = ref(false); |
|
25 |
|
26b610
|
26 |
let timer: TimeoutHandle; |
b49950
|
27 |
function stop(): void { |
V |
28 |
readyRef.value = false; |
|
29 |
timer && window.clearTimeout(timer); |
|
30 |
} |
|
31 |
function start(): void { |
|
32 |
stop(); |
|
33 |
timer = setTimeout(() => { |
|
34 |
readyRef.value = true; |
|
35 |
}, wait); |
|
36 |
} |
|
37 |
|
|
38 |
start(); |
|
39 |
|
|
40 |
tryOnUnmounted(stop); |
|
41 |
|
|
42 |
return { readyRef, stop, start }; |
|
43 |
} |