Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
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
/** Used as an internal `_.debounce` options object by `_.throttle`. */
8
var debounceOptions = {
9
'leading': false,
10
'maxWait': 0,
11
'trailing': false
12
};
13
14
/**
15
* Creates a throttled function that only invokes `func` at most once per
16
* every `wait` milliseconds. The throttled function comes with a `cancel`
17
* method to cancel delayed invocations. Provide an options object to indicate
18
* that `func` should be invoked on the leading and/or trailing edge of the
19
* `wait` timeout. Subsequent calls to the throttled function return the
20
* result of the last `func` call.
21
*
22
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
23
* on the trailing edge of the timeout only if the the throttled function is
24
* invoked more than once during the `wait` timeout.
25
*
26
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
27
* for details over the differences between `_.throttle` and `_.debounce`.
28
*
29
* @static
30
* @memberOf _
31
* @category Function
32
* @param {Function} func The function to throttle.
33
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
34
* @param {Object} [options] The options object.
35
* @param {boolean} [options.leading=true] Specify invoking on the leading
36
* edge of the timeout.
37
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
38
* edge of the timeout.
39
* @returns {Function} Returns the new throttled function.
40
* @example
41
*
42
* // avoid excessively updating the position while scrolling
43
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
44
*
45
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
46
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
47
* 'trailing': false
48
* }));
49
*
50
* // cancel a trailing throttled call
51
* jQuery(window).on('popstate', throttled.cancel);
52
*/
53
function throttle(func, wait, options) {
54
var leading = true,
55
trailing = true;
56
57
if (typeof func != 'function') {
58
throw new TypeError(FUNC_ERROR_TEXT);
59
}
60
if (options === false) {
61
leading = false;
62
} else if (isObject(options)) {
63
leading = 'leading' in options ? !!options.leading : leading;
64
trailing = 'trailing' in options ? !!options.trailing : trailing;
65
}
66
debounceOptions.leading = leading;
67
debounceOptions.maxWait = +wait;
68
debounceOptions.trailing = trailing;
69
return debounce(func, wait, debounceOptions);
70
}
71
72
module.exports = throttle;
73
74