Initial commit
[yaffs-website] / node_modules / grunt-contrib-watch / node_modules / lodash / function / throttle.js
1 var debounce = require('./debounce'),
2     isObject = require('../lang/isObject');
3
4 /** Used as the `TypeError` message for "Functions" methods. */
5 var 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 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.
14  *
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.
18  *
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`.
21  *
22  * @static
23  * @memberOf _
24  * @category Function
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.
33  * @example
34  *
35  * // avoid excessively updating the position while scrolling
36  * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
37  *
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, {
40  *   'trailing': false
41  * }));
42  *
43  * // cancel a trailing throttled call
44  * jQuery(window).on('popstate', throttled.cancel);
45  */
46 function throttle(func, wait, options) {
47   var leading = true,
48       trailing = true;
49
50   if (typeof func != 'function') {
51     throw new TypeError(FUNC_ERROR_TEXT);
52   }
53   if (options === false) {
54     leading = false;
55   } else 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, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
60 }
61
62 module.exports = throttle;