-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
55 lines (50 loc) · 975 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 防抖
* @packageDocumentation
* @module vx-hooks/useDebounceFn
*/
import { ref } from 'vue'
/**
* useDebounceFn API
*/
export interface useDebounceFnAPI {
/** 触发延时回调 */
run: (...args: any) => void;
/** 取消回调 */
cancel: () => void;
}
/**
* 防抖
* @param fn 回调函数
* @param wait { 1 } 延时时常(s)
*
* @example
* ``` ts
*
* const submit = async(d) => { console.log(d) }
* const { run, cancel } = useDebounceFn(submit, 1)
*
* run(1)
* run(2)
* run(3)
*
* // delay 1s
* => 3
*
* ```
*
*/
export function useDebounceFn<T extends (...args:any) => any>(fn: T, wait = 1): useDebounceFnAPI {
const timer = ref<any>()
const cancel = () => {
timer.value && clearTimeout(timer.value)
}
const run = (...args:any) => {
cancel()
timer.value = setTimeout(() => fn.apply(fn, args), wait * 1000)
}
return {
run,
cancel
}
}