@zendesk/react-measure-timing-hooks
Version:
react hooks for measuring time to interactive and time to render of components
70 lines • 2.25 kB
JavaScript
/**
* Copyright Zendesk, Inc.
*
* Use of this source code is governed under the Apache License, Version 2.0
* found at http://www.apache.org/licenses/LICENSE-2.0.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.debounce = exports.TimeoutReason = exports.DebounceReason = void 0;
exports.DebounceReason = Symbol('debounce');
exports.TimeoutReason = Symbol('timeout');
/**
* A simple debounce function that is easier to test against than the lodash one.
* In addition it offers a way to check whether the last call was due to a timeout or not,
* and a way to manually clear that timeout state.
* Options may change even after the debounce was created by the means of a ref.
*/
const debounce = (optionsRef) => {
let timeoutTimer;
let debounceTimer;
let lastArgs;
const cancel = () => {
if (debounceTimer)
clearTimeout(debounceTimer);
debounceTimer = undefined;
};
const reset = () => {
cancel();
if (timeoutTimer)
clearTimeout(timeoutTimer);
timeoutTimer = undefined;
const args = lastArgs;
lastArgs = undefined;
return args;
};
const flush = (reason = 'manual') => {
const args = lastArgs;
if (args) {
const shouldKeepTimeout = optionsRef.fn(...args, reason);
if (shouldKeepTimeout) {
cancel();
}
else {
reset();
}
return true;
}
reset();
return false;
};
const getIsScheduled = () => Boolean(debounceTimer) || Boolean(timeoutTimer);
return Object.assign((...args) => {
lastArgs = args;
if (debounceTimer)
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => flush(exports.DebounceReason), optionsRef.debounceMs);
if (!timeoutTimer && typeof optionsRef.timeoutMs === 'number') {
timeoutTimer = setTimeout(() => {
flush(exports.TimeoutReason);
}, optionsRef.timeoutMs);
}
}, {
flush,
cancel,
reset,
getIsScheduled,
});
};
exports.debounce = debounce;
//# sourceMappingURL=debounce.js.map
;