UNPKG

1.23 kBJavaScriptView Raw
1import debounce from './debounce.js';
2
3/**
4 * Returns a new throttled function that waits to call the callback until `duration` ms have passed. Any calls to it during that time will do nothing.
5 *
6 * @example
7 * ``` javascript
8 * import { throttle } from 'async-agent';
9 *
10 * const throttled = throttle(() => {
11 * console.log('1');
12 * });
13 *
14 * throttled();
15 * throttled();
16 * throttled();
17 * throttled();
18 *
19 * // => 1
20 * // => 1
21 * ```
22 *
23 * @function throttle
24 *
25 * @arg {Function} callback - The context and args from the last call will be passed in.
26 * @arg {Number} [duration=0]
27 * @arg {Object} [options={}]
28 * @arg {Boolean} [options.leading=true] - If true then the callback is called immediately the first time.
29 * @arg {Boolean} [options.trailing=true] - If false then the callback will only be called on the leading edge.
30 *
31 * @returns {Function} The throttled function. Has two methods: .clear() clears any current timeouts, and .flush() immediately calls any waiting callbacks.
32 */
33export default (callback, duration = 0, options = {}) => debounce(callback, duration, {
34 leading: options.leading !== false,
35 maxWait: duration,
36 trailing: options.trailing !== false
37});