UNPKG

@web3r/flowerkit

Version:

Tree-shakable JavaScript and TypeScript utility library for frontend/browser apps: DOM, events, arrays, objects, strings, date, JSON, and network helpers (ESM/CJS, SSR-friendly).

1 lines 1.98 kB
{"version":3,"file":"index.mjs","sources":[""],"sourcesContent":["export type TGetThrottledFnArgs = Parameters<typeof getThrottledFn>;\r\n\r\nexport type TGetThrottledFnReturn = ReturnType<typeof getThrottledFn>;\r\n\r\n/**\r\n * Gets a throttled function with specific delay\r\n * @template {(...args: any[]) => any} T\r\n * @param {T} func function\r\n * @param {number} [delay=1000] delay in ms, 1000 by default\r\n * @returns {(...args: Parameters<T>) => void}\r\n * @throws {TypeError} getThrottledFn: func must be a function\r\n * @throws {TypeError} getThrottledFn: delay must be a non-negative finite number\r\n * @example\r\n * // How to implement function throttling?\r\n * const getDataFromAPI = () => Promise.resolve([]);\r\n * const getThrottledDataFromAPI = getThrottledFn(getDataFromAPI, 3000);\r\n * getThrottledDataFromAPI(); // => []\r\n */\r\nexport const getThrottledFn = <T extends (...args: any[]) => any>(\r\n func: T,\r\n delay: number = 1000\r\n): ((...args: Parameters<T>) => void) => {\r\n if (typeof func !== \"function\") {\r\n throw new TypeError(\"getThrottledFn: func must be a function\");\r\n }\r\n if (typeof delay !== \"number\" || !Number.isFinite(delay) || delay < 0) {\r\n throw new TypeError(\"getThrottledFn: delay must be a non-negative finite number\");\r\n }\r\n\r\n let timeout: ReturnType<typeof setTimeout> | null = null;\r\n return (...args: Parameters<T>): void => {\r\n if (!timeout) {\r\n func(...args);\r\n timeout = setTimeout((): void => {\r\n timeout = null;\r\n }, delay);\r\n }\r\n };\r\n};\r\n"],"names":["getThrottledFn","func","delay","TypeError","Number","isFinite","timeout","args","setTimeout"],"mappings":";;;;;;;;;;;;;;AAkBO,MAAMA,eAAiBA,CAC5BC,KACAC,MAAgB,QAEhB,UAAWD,OAAS,WAClB,MAAM,IAAIE,UAAU,2CAEtB,UAAWD,QAAU,WAAaE,OAAOC,SAASH,QAAUA,MAAQ,EAClE,MAAM,IAAIC,UAAU,8DAGtB,IAAIG,QAAgD,KACpD,MAAO,IAAIC,QACT,IAAKD,QAAS,CACZL,QAAQM,MACRD,QAAUE,WAAW,KACnBF,QAAU,MACTJ,MACL"}