@wordpress/compose
Version:
WordPress higher-order components (HOCs).
117 lines (116 loc) • 3.1 kB
JavaScript
// packages/compose/src/utils/debounce/index.ts
var debounce = (func, wait, options) => {
let lastArgs;
let lastThis;
let maxWait = 0;
let result;
let timerId;
let lastCallTime;
let lastInvokeTime = 0;
let leading = false;
let maxing = false;
let trailing = true;
if (options) {
leading = !!options.leading;
maxing = "maxWait" in options;
if (options.maxWait !== void 0) {
maxWait = Math.max(options.maxWait, wait);
}
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
const args = lastArgs;
const thisArg = lastThis;
lastArgs = void 0;
lastThis = void 0;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function startTimer(pendingFunc, waitTime) {
timerId = setTimeout(pendingFunc, waitTime);
}
function cancelTimer() {
if (timerId !== void 0) {
clearTimeout(timerId);
}
}
function leadingEdge(time) {
lastInvokeTime = time;
startTimer(timerExpired, wait);
return leading ? invokeFunc(time) : result;
}
function getTimeSinceLastCall(time) {
return time - (lastCallTime || 0);
}
function remainingWait(time) {
const timeSinceLastCall = getTimeSinceLastCall(time);
const timeSinceLastInvoke = time - lastInvokeTime;
const timeWaiting = wait - timeSinceLastCall;
return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
const timeSinceLastCall = getTimeSinceLastCall(time);
const timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
const time = Date.now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
startTimer(timerExpired, remainingWait(time));
return void 0;
}
function clearTimer() {
timerId = void 0;
}
function trailingEdge(time) {
clearTimer();
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = void 0;
return result;
}
function cancel() {
cancelTimer();
lastInvokeTime = 0;
clearTimer();
lastArgs = lastCallTime = lastThis = void 0;
}
function flush() {
return pending() ? trailingEdge(Date.now()) : result;
}
function pending() {
return timerId !== void 0;
}
function debounced(...args) {
const time = Date.now();
const isInvoking = shouldInvoke(time);
lastArgs = args;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (!pending()) {
return leadingEdge(lastCallTime);
}
if (maxing) {
startTimer(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (!pending()) {
startTimer(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
debounced.pending = pending;
return debounced;
};
export {
debounce
};
//# sourceMappingURL=index.js.map