-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.js
63 lines (61 loc) · 1.56 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function throttle(func, wait) {
let inThrottle = false;
return function(args) {
if (inThrottle) return;
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, wait);
};
}
function throttle(func, wait) {
let timeout = null;
let lastRanAt;
return function(...args) {
if (lastRanAt) {
clearTimeout(timeout);
timeout = setTimeout(() => {
if (Date.now() - lastRanAt >= wait) {
func.apply(this, args);
lastRanAt = Date.now();
}
}, wait - (Date.now() - lastRanAt));
} else {
func.apply(this, args);
lastRanAt = Date.now();
}
};
}
// underscore version
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}