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/. */
7 // setImmediate is only defined when running in the worker thread
8 /* globals setImmediate */
11 * From underscore's `_.throttle`
12 * http://underscorejs.org
13 * (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14 * Underscore may be freely distributed under the MIT license.
16 * Returns a function, that, when invoked, will only be triggered at most once during a
17 * given window of time. The throttled function will run as much as it can, without ever
18 * going more than once per wait duration.
20 * @param {Function} func
21 * The function to throttle
22 * @param {number} wait
24 * @param {Object} scope
25 * The scope to use for func
26 * @return {Function} The throttled function
28 function throttle(func
, wait
, scope
) {
33 const later = function () {
34 previous
= Date
.now();
36 result
= func
.apply(scope
, args
);
40 const throttledFunction = function () {
41 const now
= Date
.now();
42 const remaining
= wait
- (now
- previous
);
46 clearTimeout(timeout
);
50 result
= func
.apply(scope
, args
);
52 } else if (!timeout
) {
53 // On worker thread, we don't have access to privileged setTimeout/clearTimeout
54 // API which wouldn't be frozen when the worker is paused. So rely on the privileged
55 // setImmediate function which executes on the next event loop.
60 timeout
= setTimeout(later
, remaining
);
69 clearTimeout(timeout
);
83 return throttledFunction();
86 throttledFunction
.cancel
= cancel
;
87 throttledFunction
.flush
= flush
;
89 return throttledFunction
;
92 exports
.throttle
= throttle
;