Open History to see the last commit
1export interface AsyncThrottleOptions {
2 interval?: number
3 onError?: (error: unknown) => void
4}
5β
6const noop = () => {
7 /* do nothing */
8}
9β
10export function asyncThrottle<Args extends readonly unknown[]>(
11 func: (...args: Args) => Promise<void>,
12 { interval = 1000, onError = noop }: AsyncThrottleOptions = {}
13) {
14 if (typeof func !== 'function') throw new Error('argument is not function.')
15β
16 let running = false
17 let lastTime = 0
18 let timeout: ReturnType<typeof setTimeout>
19 let currentArgs: Args | null = null
20β
21 const execFunc = async () => {
22 if (currentArgs) {
23 const args = currentArgs
24 currentArgs = null
25 try {
26 running = true
27 await func(...args)
28 } catch (error) {
29 onError(error)
30 } finally {
31 lastTime = Date.now() // this line must after 'func' executed to avoid two 'func' running in concurrent.
32 running = false
33 }
34 }
35 }
36β
37 const delayFunc = async () => {
38 clearTimeout(timeout)
39 timeout = setTimeout(() => {
40 if (running) {
41 delayFunc() // Will come here when 'func' execution time is greater than the interval.
42 } else {
43 execFunc()
44 }
45 }, interval)
46 }
47β
48 return (...args: Args) => {
49 currentArgs = args
50β
51 const tooSoon = Date.now() - lastTime < interval
52 if (running || tooSoon) {
53 delayFunc()
54 } else {
55 execFunc()
56 }
57 }
58}