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