MCPcopy
hub / github.com/axios/axios / throttle

Function throttle

lib/helpers/throttle.js:7–42  ·  view source on GitHub ↗

* Throttle decorator * @param {Function} fn * @param {Number} freq * @return {Function}

(fn, freq)

Source from the content-addressed store, hash-verified

5 * @return {Function}
6 */
7function throttle(fn, freq) {
8 let timestamp = 0;
9 let threshold = 1000 / freq;
10 let lastArgs;
11 let timer;
12
13 const invoke = (args, now = Date.now()) => {
14 timestamp = now;
15 lastArgs = null;
16 if (timer) {
17 clearTimeout(timer);
18 timer = null;
19 }
20 fn(...args);
21 };
22
23 const throttled = (...args) => {
24 const now = Date.now();
25 const passed = now - timestamp;
26 if (passed >= threshold) {
27 invoke(args, now);
28 } else {
29 lastArgs = args;
30 if (!timer) {
31 timer = setTimeout(() => {
32 timer = null;
33 invoke(lastArgs);
34 }, threshold - passed);
35 }
36 }
37 };
38
39 const flush = () => lastArgs && invoke(lastArgs);
40
41 return [throttled, flush];
42}
43
44export default throttle;

Callers 1

progressEventReducerFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected