froebel
Version:
TypeScript utility library
41 lines (38 loc) • 1.11 kB
JavaScript
const {
performance
} = "performance" in globalThis ? globalThis : {performance:{now:()=>Date.now()}};
export const cancel = Symbol("throttle.cancel");
/**
* Create a throttled function that invokes `fun` at most every `ms` milliseconds.
*
* `fun` is invoked with the last arguments passed to the throttled function.
*
* Calling `[throttle.cancel]()` on the throttled function will cancel the currently
* scheduled invocation.
*/
const throttle = Object.assign((fun, ms, {
leading = true,
trailing = true
} = {}) => {
let toId;
let lastInvoke = -Infinity;
let lastArgs;
const invoke = () => {
lastInvoke = performance.now();
toId = undefined;
fun(...lastArgs);
};
return Object.assign((...args) => {
if (!leading && !trailing) return;
lastArgs = args;
const dt = performance.now() - lastInvoke;
if (dt >= ms && toId === undefined && leading) invoke();else if (toId === undefined && trailing) {
toId = setTimeout(invoke, dt >= ms ? ms : ms - dt);
}
}, {
[cancel]: () => clearTimeout(toId)
});
}, {
cancel
});
export default throttle;