-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththrottle.js
35 lines (34 loc) · 918 Bytes
/
throttle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function throttle(fn, delay) {
let last = 0;
return function () {
const now = +new Date();
if (now - last > delay) {
fn.apply(this, arguments);
last = now;
}
};
}
function opThrottle(fn, delay, { leading = false, trailing = true } = {}) {
let last = 0;
let timer = null;
return function () {
const now = +new Date();
if (!last && leading === false) {
last = now;
}
if (now - last > delay) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(this, arguments);
last = now;
} else if (!timer && trailing !== false) {
timer = setTimeout(() => {
fn.apply(this, arguments);
last = +new Date();
timer = null;
}, delay);
}
};
}