Open History to see the last commit
1import { noop } from './utils'
2β
3interface AsyncThrottleOptions {
4 interval?: number
5 onError?: (error: unknown) => void
6}
7β
8export function asyncThrottle<TArgs extends ReadonlyArray<unknown>>(
9 func: (...args: TArgs) => Promise<void>,
10 { interval = 1000, onError = noop }: AsyncThrottleOptions = {},
11) {
12 if (typeof func !== 'function') throw new Error('argument is not function.')
13β
14 let nextExecutionTime = 0
15 let lastArgs = null
16 let isExecuting = false
17 let isScheduled = false
18β
19 return async (...args: TArgs) => {
20 lastArgs = args
21 if (isScheduled) return
22 isScheduled = true
23 while (isExecuting) {
24 await new Promise((done) => setTimeout(done, interval))
25 }
26 while (Date.now() < nextExecutionTime) {
27 await new Promise((done) =>
28 setTimeout(done, nextExecutionTime - Date.now()),
29 )
30 }
31 isScheduled = false
32 isExecuting = true
33 try {
34 await func(...lastArgs)
35 } catch (error) {
36 try {
37 onError(error)
38 } catch {}
39 }
40 nextExecutionTime = Date.now() + interval
41 isExecuting = false
42 }
43}