* Throttle decorator * @param {Function} fn * @param {Number} freq * @return {Function}
(fn, freq)
| 5 | * @return {Function} |
| 6 | */ |
| 7 | function 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 | |
| 44 | export default throttle; |
no outgoing calls
no test coverage detected