-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
73 lines (62 loc) · 1.33 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { ref } from 'vue-demi'
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref } from '@vueuse/shared'
import { tryOnScopeDispose } from '../tryOnScopeDispose'
import type { Stoppable } from '../utils'
import { isClient } from '../utils'
export interface UseTimeoutFnOptions {
/**
* Start the timer immediate after calling this function
*
* @default true
*/
immediate?: boolean
}
/**
* Wrapper for `setTimeout` with controls.
*
* @param cb
* @param interval
* @param immediate
*/
export function useTimeoutFn(
cb: (...args: unknown[]) => any,
interval: MaybeComputedRef<number>,
options: UseTimeoutFnOptions = {},
): Stoppable {
const {
immediate = true,
} = options
const isPending = ref(false)
let timer: number | null = null
function clear() {
if (timer) {
clearTimeout(timer)
timer = null
}
}
function stop() {
isPending.value = false
clear()
}
function start(...args: unknown[]) {
clear()
isPending.value = true
timer = setTimeout(() => {
isPending.value = false
timer = null
cb(...args)
}, resolveUnref(interval)) as unknown as number
}
if (immediate) {
isPending.value = true
if (isClient)
start()
}
tryOnScopeDispose(stop)
return {
isPending,
start,
stop,
}
}