1 var debounce = require('./debounce'),
2 isObject = require('./isObject');
4 /** Used as the `TypeError` message for "Functions" methods. */
5 var FUNC_ERROR_TEXT = 'Expected a function';
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.
17 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
18 * on the trailing edge of the timeout only if the throttled function is
19 * invoked more than once during the `wait` timeout.
21 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
22 * for details over the differences between `_.throttle` and `_.debounce`.
27 * @param {Function} func The function to throttle.
28 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
29 * @param {Object} [options] The options object.
30 * @param {boolean} [options.leading=true] Specify invoking on the leading
31 * edge of the timeout.
32 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
33 * edge of the timeout.
34 * @returns {Function} Returns the new throttled function.
37 * // Avoid excessively updating the position while scrolling.
38 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
40 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
41 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
42 * jQuery(element).on('click', throttled);
44 * // Cancel the trailing throttled invocation.
45 * jQuery(window).on('popstate', throttled.cancel);
47 function throttle(func, wait, options) {
51 if (typeof func != 'function') {
52 throw new TypeError(FUNC_ERROR_TEXT);
54 if (isObject(options)) {
55 leading = 'leading' in options ? !!options.leading : leading;
56 trailing = 'trailing' in options ? !!options.trailing : trailing;
58 return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing });
61 module.exports = throttle;