forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseDebounce.ts
More file actions
52 lines (39 loc) · 1.47 KB
/
useDebounce.ts
File metadata and controls
52 lines (39 loc) · 1.47 KB
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
import { shallowRef, watch, type MaybeRefOrGetter, type Ref } from 'vue'
import { useState } from './useState'
type FunctionArgs = (...args: any[]) => any
const DEFAULT_TIMEOUT = 100
export function useDebounceFn<T extends FunctionArgs>(
fn: T,
ms?: MaybeRefOrGetter<number>
): T {
let timeoutId: ReturnType<typeof setTimeout> | undefined
const resolveDelay = (ms: MaybeRefOrGetter<number> | undefined): number => {
if (typeof ms === 'function') {
return ms()
} else if (typeof ms === 'object' && 'value' in ms) {
return ms.value
} else if (typeof ms === 'number') {
return ms
} else {
return DEFAULT_TIMEOUT
}
}
const debounced = ((...args: Parameters<T>) => {
timeoutId && clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
fn(...args)
}, resolveDelay(ms))
}) as T
return debounced
}
export function useDebounce<T>(original: Ref<T>, ms?: MaybeRefOrGetter<number>): Ref<T> {
const inner = shallowRef<T>(original.value)
const debouncedFn = useDebounceFn((newValue: T) => inner.value = newValue, ms)
watch(original, newVal => debouncedFn(newVal))
return inner
}
export function useDebounceState<T>(defaultValue: T, ms?: MaybeRefOrGetter<number>): [Ref<T>, ArgCallback<T>] {
const [inner, setInner] = useState<T>(defaultValue)
const debouncedSet = useDebounceFn(setInner, ms)
return [inner, debouncedSet]
}