1 | function throttle(fn, threshold = 250, scope) {
|
2 | let lastTime = 0;
|
3 | let deferTimer;
|
4 | return function (...args) {
|
5 | const context = scope || this;
|
6 | const now = Date.now();
|
7 | if (now - lastTime > threshold) {
|
8 | fn.apply(this, args);
|
9 | lastTime = now;
|
10 | }
|
11 | else {
|
12 | clearTimeout(deferTimer);
|
13 | deferTimer = setTimeout(() => {
|
14 | lastTime = now;
|
15 | fn.apply(context, args);
|
16 | }, threshold);
|
17 | }
|
18 | };
|
19 | }
|
20 | function debounce(fn, ms = 250, scope) {
|
21 | let timer;
|
22 | return function (...args) {
|
23 | const context = scope || this;
|
24 | clearTimeout(timer);
|
25 | timer = setTimeout(function () {
|
26 | fn.apply(context, args);
|
27 | }, ms);
|
28 | };
|
29 | }
|
30 |
|
31 | export { debounce as d, throttle as t };
|