-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.js
59 lines (56 loc) · 1.66 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
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
var throttle = function(callback, limit) {
var wait = false;
return function() {
if (!wait) {
callback.call();
wait = true;
setTimeout(function() {
wait = false;
}, limit);
}
};
};
// More elaborate Underscore method
function throttle(func, wait, options) {
var _ = {
now: Date.now || function() {
return new Date().getTime();
}
}
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.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;
};
};
// Usage
var myEfficientFn = throttle(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener('scroll', myEfficientFn);