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β
9/**
10 * Wraps an async function so it runs at most once per `interval`, never concurrently, and with the
11 * arguments of the latest call. Calls made while a run is scheduled only update those arguments.
12 * @param func - The async function to throttle.
13 * @param options - The `interval` between runs in milliseconds, and `onError`, called when `func`
14 * rejects.
15 * @returns The throttled function.
16 * @throws {Error} If `func` is not a function.
17 */
18export function asyncThrottle<TArgs extends ReadonlyArray<unknown>>(
19 func: (...args: TArgs) => Promise<void>,
20 { interval = 1000, onError = noop }: AsyncThrottleOptions = {},
21) {
22 if (typeof func !== 'function') throw new Error('argument is not function.')
23β
24 let nextExecutionTime = 0
25 let lastArgs = null
26 let isExecuting = false
27 let isScheduled = false
28β
29 return async (...args: TArgs) => {
30 lastArgs = args
31 if (isScheduled) return
32 isScheduled = true
33 while (isExecuting) {
34 await new Promise((done) => timeoutManager.setTimeout(done, interval))
35 }
36 while (Date.now() < nextExecutionTime) {
37 await new Promise((done) =>
38 timeoutManager.setTimeout(done, nextExecutionTime - Date.now()),
39 )
40 }
41 isScheduled = false
42 isExecuting = true
43 try {
44 await func(...lastArgs)
45 } catch (error) {
46 try {
47 onError(error)
48 } catch {}
49 }
50 nextExecutionTime = Date.now() + interval
51 isExecuting = false
52 }
53}