2017-11-17 22:27:35 +01:00
|
|
|
// Taken from underscore.js (slightly modified to add the getNow function and use const/let over var)
|
|
|
|
// https://github.com/jashkenas/underscore/blob/master/underscore.js#L830-L874
|
|
|
|
|
|
|
|
// Returns a function, that, when invoked, will only be triggered at most once
|
|
|
|
// during a given window of time. Normally, the throttled function will run
|
|
|
|
// as much as it can, without ever going more than once per `wait` duration;
|
|
|
|
// but if you'd like to disable the execution on the leading edge, pass
|
|
|
|
// `{leading: false}`. To disable execution on the trailing edge, ditto.
|
2017-12-21 18:32:51 +01:00
|
|
|
export default function throttle(func, wait, options = {}) {
|
|
|
|
let timeout;
|
|
|
|
let context;
|
|
|
|
let args;
|
|
|
|
let result;
|
2017-11-17 22:27:35 +01:00
|
|
|
let previous = 0;
|
|
|
|
const getNow = () => new Date().getTime();
|
|
|
|
|
2017-12-28 00:48:11 +01:00
|
|
|
const later = () => {
|
2017-11-17 22:27:35 +01:00
|
|
|
previous = options.leading === false ? 0 : getNow();
|
|
|
|
timeout = null;
|
|
|
|
result = func.apply(context, args);
|
2017-12-21 18:32:51 +01:00
|
|
|
if (!timeout) {
|
|
|
|
context = null;
|
|
|
|
args = null;
|
|
|
|
}
|
2017-11-17 22:27:35 +01:00
|
|
|
};
|
|
|
|
|
2017-12-28 00:48:11 +01:00
|
|
|
const throttled = function throttled(...funcArgs) {
|
2017-11-17 22:27:35 +01:00
|
|
|
const now = getNow();
|
|
|
|
|
|
|
|
if (!previous && options.leading === false) previous = now;
|
|
|
|
|
|
|
|
const remaining = wait - (now - previous);
|
|
|
|
|
|
|
|
context = this;
|
2017-12-21 18:32:51 +01:00
|
|
|
args = funcArgs;
|
2017-11-17 22:27:35 +01:00
|
|
|
|
|
|
|
if (remaining <= 0 || remaining > wait) {
|
|
|
|
if (timeout) {
|
|
|
|
clearTimeout(timeout);
|
|
|
|
timeout = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
previous = now;
|
|
|
|
result = func.apply(context, args);
|
|
|
|
|
2017-12-21 18:32:51 +01:00
|
|
|
if (!timeout) {
|
|
|
|
context = null;
|
|
|
|
args = null;
|
|
|
|
}
|
2017-11-17 22:27:35 +01:00
|
|
|
} else if (!timeout && options.trailing !== false) {
|
|
|
|
timeout = setTimeout(later, remaining);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
};
|
|
|
|
|
2017-12-28 00:48:11 +01:00
|
|
|
throttled.cancel = () => {
|
2017-11-17 22:27:35 +01:00
|
|
|
clearTimeout(timeout);
|
|
|
|
previous = 0;
|
2017-12-21 18:32:51 +01:00
|
|
|
timeout = null;
|
|
|
|
context = null;
|
|
|
|
args = null;
|
2017-11-17 22:27:35 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
return throttled;
|
|
|
|
}
|