main
Last change
on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago |
Initial commit
|
-
Property mode
set to
100644
|
File size:
702 bytes
|
Rev | Line | |
---|
[d24f17c] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | /**
|
---|
| 4 | * Throttle decorator
|
---|
| 5 | * @param {Function} fn
|
---|
| 6 | * @param {Number} freq
|
---|
| 7 | * @return {Function}
|
---|
| 8 | */
|
---|
| 9 | function throttle(fn, freq) {
|
---|
| 10 | let timestamp = 0;
|
---|
| 11 | const threshold = 1000 / freq;
|
---|
| 12 | let timer = null;
|
---|
| 13 | return function throttled(force, args) {
|
---|
| 14 | const now = Date.now();
|
---|
| 15 | if (force || now - timestamp > threshold) {
|
---|
| 16 | if (timer) {
|
---|
| 17 | clearTimeout(timer);
|
---|
| 18 | timer = null;
|
---|
| 19 | }
|
---|
| 20 | timestamp = now;
|
---|
| 21 | return fn.apply(null, args);
|
---|
| 22 | }
|
---|
| 23 | if (!timer) {
|
---|
| 24 | timer = setTimeout(() => {
|
---|
| 25 | timer = null;
|
---|
| 26 | timestamp = Date.now();
|
---|
| 27 | return fn.apply(null, args);
|
---|
| 28 | }, threshold - (now - timestamp));
|
---|
| 29 | }
|
---|
| 30 | };
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | export default throttle;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.