UNPKG

froebel

Version:
51 lines (46 loc) 1.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.cancel = void 0; const { performance } = "performance" in globalThis ? globalThis : require("perf_hooks"); 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. */ exports.cancel = cancel; 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 }); var _default = throttle; exports.default = _default; module.exports = Object.assign(exports.default || {}, exports);