@react-md/utils
Version:
General utils for react-md.
77 lines • 2.98 kB
JavaScript
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
/**
* Creates a throttled version of a function so that it'll be called with
* trailing and leading calls. Since I always get this confused with `debounce`,
* here's a quick summary of the differences:
*
* - debounce will wait to call the function until it hasn't been called again
* for the wait duration without trailing or leading calls. If it has the
* trailing and leading calls, I can't figure out how it's different than
* throttle.
* - throttle will be called each time it is available to be called.
*
* So debounce is great for things like auto-save features if you want to save
* whenever the user stops typing for a few seconds while throttle is good for
* things like sending an API request when the user is typing so that it isn't
* sent every keystroke, but every few letters. You _could_ also do debounce
* here, but it'll feel more "responsive" to the user when throttled.
*
* @param fn - The function that should be throttled
* @param wait - The number of milliseconds to wait before calling the function
* again
* @returns a throttled version of the function that'll return the last computed
* value if it was called again during the "wait" period.
*/
export function throttle(fn, wait) {
var lastCalledTime = 0;
var timeout;
var result;
var args;
function trailingCall() {
lastCalledTime = Date.now();
timeout = undefined;
result = fn.apply(void 0, __spreadArray([], __read(args), false));
}
return function throttled() {
var nextArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
nextArgs[_i] = arguments[_i];
}
args = nextArgs;
var now = Date.now();
var remaining = wait - (now - lastCalledTime);
if (remaining <= 0 || remaining > wait) {
lastCalledTime = now;
result = fn.apply(void 0, __spreadArray([], __read(args), false));
}
else if (!timeout) {
timeout = window.setTimeout(trailingCall, remaining);
}
return result;
};
}
//# sourceMappingURL=throttle.js.map