rc-js-util
Version:
A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.
57 lines • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fpDebounce = void 0;
/**
* @public
* Creates a function that will proxy calls to `functionToProxy` when `wait` time has passed since the last call, using the
* most recent arguments. Where `immediate` is true, the function immediately proxies the call and will not proxy again until
* `wait` time passes since the last call.
*
* @param functionToProxy - The function to debounce.
* @param wait - Time to wait in ms.
* @param immediate - If true run on the leading edge, default false.
* @returns A debounced function.
*
* @remarks
* As per underscore's debounce, except that returns have been disallowed.
* See {@link fpDebounce}.
*/
function fpDebounce(wait, immediate, functionToProxy) {
let timeout;
let previous;
let args;
let context;
function later() {
const passed = Date.now() - previous;
if (wait > passed) {
timeout = setTimeout(later, wait - passed);
}
else {
timeout = undefined;
if (!immediate) {
functionToProxy.apply(context, args);
}
// This check is needed because `func` can recursively invoke `debounced`.
if (timeout == null) {
args = context = null;
}
}
}
const debounced = function (..._args) {
args = _args;
previous = Date.now();
if (timeout == null) {
timeout = setTimeout(later, wait);
if (immediate) {
functionToProxy.apply(this, args);
}
}
return timeout;
};
debounced.cancel = function () {
clearTimeout(timeout);
};
return debounced;
}
exports.fpDebounce = fpDebounce;
//# sourceMappingURL=fp-debounce.js.map