UNPKG

2.66 kBTypeScriptView Raw
1import { CallOptions, DebouncedState } from './useDebouncedCallback';
2/**
3 * Creates a throttled function that only invokes `func` at most once per
4 * every `wait` milliseconds (or once per browser frame).
5 *
6 * The throttled function comes with a `cancel` method to cancel delayed `func`
7 * invocations and a `flush` method to immediately invoke them.
8 *
9 * Provide `options` to indicate whether `func` should be invoked on the leading
10 * and/or trailing edge of the `wait` timeout. The `func` is invoked with the
11 * last arguments provided to the throttled function.
12 *
13 * Subsequent calls to the throttled function return the result of the last
14 * `func` invocation.
15 *
16 * **Note:** If `leading` and `trailing` options are `true`, `func` is
17 * invoked on the trailing edge of the timeout only if the throttled function
18 * is invoked more than once during the `wait` timeout.
19 *
20 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
21 * until the next tick, similar to `setTimeout` with a timeout of `0`.
22 *
23 * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
24 * invocation will be deferred until the next frame is drawn (typically about
25 * 16ms).
26 *
27 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
28 * for details over the differences between `throttle` and `debounce`.
29 *
30 * @category Function
31 * @param {Function} func The function to throttle.
32 * @param {number} [wait=0]
33 * The number of milliseconds to throttle invocations to; if omitted,
34 * `requestAnimationFrame` is used (if available, otherwise it will be setTimeout(...,0)).
35 * @param {Object} [options={}] The options object.
36 * @param {boolean} [options.leading=true]
37 * Specify invoking on the leading edge of the timeout.
38 * @param {boolean} [options.trailing=true]
39 * Specify invoking on the trailing edge of the timeout.
40 * @returns {Function} Returns the new throttled function.
41 * @example
42 *
43 * // Avoid excessively updating the position while scrolling.
44 * const scrollHandler = useThrottledCallback(updatePosition, 100)
45 * window.addEventListener('scroll', scrollHandler)
46 *
47 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
48 * const throttled = useThrottledCallback(renewToken, 300000, { 'trailing': false })
49 * <button onClick={throttled}>click</button>
50 *
51 * // Cancel the trailing throttled invocation.
52 * window.addEventListener('popstate', throttled.cancel);
53 */
54export default function useThrottledCallback<T extends (...args: any) => ReturnType<T>>(func: T, wait: number, { leading, trailing }?: CallOptions): DebouncedState<T>;