main
Last change
on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
861 bytes
|
Rev | Line | |
---|
[d565449] | 1 | /**
|
---|
| 2 | * Throttle decorator
|
---|
| 3 | * @param {Function} fn
|
---|
| 4 | * @param {Number} 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.apply(null, 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;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.