Bug 1859954 - Use XP_DARWIN rather than XP_MACOS in PHC r=glandium
[gecko.git] / devtools / shared / throttle.js
blob85d0514f984c9795bad70bef6d4bdeaa02e235f9
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/. */
5 "use strict";
7 /**
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.
12  *
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.
16  *
17  * @param  {Function} func
18  *         The function to throttle
19  * @param  {number} wait
20  *         The wait period
21  * @param  {Object} scope
22  *         The scope to use for func
23  * @return {Function} The throttled function
24  */
25 function throttle(func, wait, scope) {
26   let args, result;
27   let timeout = null;
28   let previous = 0;
30   const later = function () {
31     previous = Date.now();
32     timeout = null;
33     result = func.apply(scope, args);
34     args = null;
35   };
37   const throttledFunction = function () {
38     const now = Date.now();
39     const remaining = wait - (now - previous);
40     args = arguments;
41     if (remaining <= 0) {
42       clearTimeout(timeout);
43       timeout = null;
44       previous = now;
45       result = func.apply(scope, args);
46       args = null;
47     } else if (!timeout) {
48       timeout = setTimeout(later, remaining);
49     }
50     return result;
51   };
53   function cancel() {
54     if (timeout) {
55       clearTimeout(timeout);
56       timeout = null;
57     }
58     previous = 0;
59     args = undefined;
60     result = undefined;
61   }
63   function flush() {
64     if (!timeout) {
65       return result;
66     }
67     previous = 0;
68     return throttledFunction();
69   }
71   throttledFunction.cancel = cancel;
72   throttledFunction.flush = flush;
74   return throttledFunction;
77 exports.throttle = throttle;