@mightyplow/jslib
Version:
js helpers library
34 lines (31 loc) • 947 B
JavaScript
/**
* Creates a function which debounces with the given timeout and resets the timer
* on every function call.
*
* The returned debounced function has a function property abort() which aborts the timer.
*
* @memberOf function
* @function
* @param {function} fn
* @param {number} timeout
* @return {function(...[*])}
*/
export default (function (fn) {
var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var timer = null;
var abort = function abort() {
return clearTimeout(timer);
};
// extend function with abort method
return Object.assign(function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
abort();
timer = setTimeout(function () {
return fn.apply(undefined, args);
}, timeout);
}, {
abort: abort
});
});