@n1ru4l/in-memory-live-query-store
Version:
[](https://www.npmjs.com/package/@n1ru4l/in-memory-live-query-store) [](https://www.np
41 lines (40 loc) • 1.02 kB
JavaScript
/**
* Creates a throttled function that only invokes func at most once per every wait milliseconds.
*/
export const throttle = (fn, wait) => {
let timeout;
let lastCalled = 0;
let cancelled = false;
const exec = (...args) => {
if (!cancelled) {
fn(...args);
lastCalled = Date.now();
}
};
const run = (...args) => {
if (cancelled) {
return;
}
const timeToNextTick = Math.max(0, wait - (Date.now() - lastCalled));
if (!timeToNextTick) {
// first execution, or wait === 0
exec(...args);
}
else {
clearTimeout(timeout);
timeout = setTimeout(() => {
if (Date.now() - lastCalled >= wait) {
exec(...args);
}
}, timeToNextTick);
}
};
const cancel = () => {
cancelled = true;
clearTimeout(timeout);
};
return {
run,
cancel,
};
};