UNPKG

2.59 kBJavaScriptView Raw
1import debounce from './debounce';
2import isObject from './isObject';
3
4/** Used as the `TypeError` message for "Functions" methods. */
5var FUNC_ERROR_TEXT = 'Expected a function';
6
7/**
8 * Creates a throttled function that only invokes `func` at most once per
9 * every `wait` milliseconds. The throttled function comes with a `cancel`
10 * method to cancel delayed `func` invocations and a `flush` method to
11 * immediately invoke them. Provide an options object to indicate whether
12 * `func` should be invoked on the leading and/or trailing edge of the `wait`
13 * timeout. The `func` is invoked with the last arguments provided to the
14 * throttled function. Subsequent calls to the throttled function return the
15 * result of the last `func` invocation.
16 *
17 * **Note:** If `leading` and `trailing` options are `true`, `func` is
18 * invoked on the trailing edge of the timeout only if the throttled function
19 * is invoked more than once during the `wait` timeout.
20 *
21 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
22 * for details over the differences between `_.throttle` and `_.debounce`.
23 *
24 * @static
25 * @memberOf _
26 * @since 0.1.0
27 * @category Function
28 * @param {Function} func The function to throttle.
29 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
30 * @param {Object} [options={}] The options object.
31 * @param {boolean} [options.leading=true]
32 * Specify invoking on the leading edge of the timeout.
33 * @param {boolean} [options.trailing=true]
34 * Specify invoking on the trailing edge of the timeout.
35 * @returns {Function} Returns the new throttled function.
36 * @example
37 *
38 * // Avoid excessively updating the position while scrolling.
39 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
40 *
41 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
42 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
43 * jQuery(element).on('click', throttled);
44 *
45 * // Cancel the trailing throttled invocation.
46 * jQuery(window).on('popstate', throttled.cancel);
47 */
48function throttle(func, wait, options) {
49 var leading = true,
50 trailing = true;
51
52 if (typeof func != 'function') {
53 throw new TypeError(FUNC_ERROR_TEXT);
54 }
55 if (isObject(options)) {
56 leading = 'leading' in options ? !!options.leading : leading;
57 trailing = 'trailing' in options ? !!options.trailing : trailing;
58 }
59 return debounce(func, wait, {
60 'leading': leading,
61 'maxWait': wait,
62 'trailing': trailing
63 });
64}
65
66export default throttle;