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