Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

asyncThrottle.ts

55 lines1.6 KB

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