1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * From underscore's `_.throttle`
9 * http://underscorejs.org
10 * (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
11 * Underscore may be freely distributed under the MIT license.
13 * Returns a function, that, when invoked, will only be triggered at most once during a
14 * given window of time. The throttled function will run as much as it can, without ever
15 * going more than once per wait duration.
17 * @param {Function} func
18 * The function to throttle
19 * @param {number} wait
21 * @param {Object} scope
22 * The scope to use for func
23 * @return {Function} The throttled function
25 function throttle(func, wait, scope) {
30 const later = function() {
31 previous = Date.now();
33 result = func.apply(scope, args);
37 const throttledFunction = function() {
38 const now = Date.now();
39 const remaining = wait - (now - previous);
42 clearTimeout(timeout);
45 result = func.apply(scope, args);
47 } else if (!timeout) {
48 timeout = setTimeout(later, remaining);
55 clearTimeout(timeout);
68 return throttledFunction();
71 throttledFunction.cancel = cancel;
72 throttledFunction.flush = flush;
74 return throttledFunction;
77 exports.throttle = throttle;