1 var debounce = require('./debounce'),
2 isObject = require('../lang/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 invocations. Provide an options object to indicate
11 * that `func` should be invoked on the leading and/or trailing edge of the
12 * `wait` timeout. Subsequent calls to the throttled function return the
13 * result of the last `func` call.
15 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
16 * on the trailing edge of the timeout only if the the throttled function is
17 * invoked more than once during the `wait` timeout.
19 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
20 * for details over the differences between `_.throttle` and `_.debounce`.
25 * @param {Function} func The function to throttle.
26 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
27 * @param {Object} [options] The options object.
28 * @param {boolean} [options.leading=true] Specify invoking on the leading
29 * edge of the timeout.
30 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
31 * edge of the timeout.
32 * @returns {Function} Returns the new throttled function.
35 * // avoid excessively updating the position while scrolling
36 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
38 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
39 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
43 * // cancel a trailing throttled call
44 * jQuery(window).on('popstate', throttled.cancel);
46 function throttle(func, wait, options) {
50 if (typeof func != 'function') {
51 throw new TypeError(FUNC_ERROR_TEXT);
53 if (options === false) {
55 } else if (isObject(options)) {
56 leading = 'leading' in options ? !!options.leading : leading;
57 trailing = 'trailing' in options ? !!options.trailing : trailing;
59 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
62 module.exports = throttle;