@sorens/artist-svelte
Version:
an opinionated and clean UI framework for SvelteKit with theme support built-in
57 lines (56 loc) • 2.01 kB
JavaScript
/**
*
*
*
*/
export default function debounce(func, waitMilliseconds = 50, options = {}) {
var _a, _b;
let timeoutId;
const isImmediate = (_a = options.isImmediate) !== null && _a !== void 0 ? _a : false;
const callback = (_b = options.callback) !== null && _b !== void 0 ? _b : false;
const maxWait = options.maxWait;
let lastInvokeTime = Date.now();
let promises = [];
function nextInvokeTimeout() {
if (maxWait !== undefined) {
const timeSinceLastInvocation = Date.now() - lastInvokeTime;
if (timeSinceLastInvocation + waitMilliseconds >= maxWait) {
return maxWait - timeSinceLastInvocation;
}
}
return waitMilliseconds;
}
const debouncedFunction = function (...args) {
return new Promise((resolve, reject) => {
const invokeFunction = () => {
timeoutId = undefined;
lastInvokeTime = Date.now();
if (!isImmediate) {
const result = func.apply(this, args);
callback && callback(result);
promises.forEach(({ resolve }) => resolve(result));
promises = [];
}
};
const shouldCallNow = isImmediate && timeoutId === undefined;
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(invokeFunction, nextInvokeTimeout());
if (shouldCallNow) {
const result = func.apply(this, args);
callback && callback(result);
return resolve(result);
}
promises.push({ resolve, reject });
});
};
debouncedFunction.cancel = function (reason) {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
promises.forEach(({ reject }) => reject(reason));
promises = [];
};
return debouncedFunction;
}