summaryrefslogtreecommitdiff
path: root/shared/components/src/utils/throttle.ts
diff options
context:
space:
mode:
authorrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
committerrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
commitbce557cc2dc767628bed6aac87301a1be7c5431b (patch)
treeb51a051228d01fe3306cd7626d4a96768aadb944 /shared/components/src/utils/throttle.ts
init commit
Diffstat (limited to 'shared/components/src/utils/throttle.ts')
-rw-r--r--shared/components/src/utils/throttle.ts49
1 files changed, 49 insertions, 0 deletions
diff --git a/shared/components/src/utils/throttle.ts b/shared/components/src/utils/throttle.ts
new file mode 100644
index 0000000..b5e36bc
--- /dev/null
+++ b/shared/components/src/utils/throttle.ts
@@ -0,0 +1,49 @@
+/* eslint-disable import/prefer-default-export */
+/**
+ * @name throttle
+ * @description
+ * Creates a throttled function that only invokes func at most once per every limit time (ms).
+ *
+ * *NOTE: this does not capture or recall all functions that were triggered.
+ * This will drop function calls that happen during the throttle time*
+ * @param limit - time to wait between calls in ms
+ * @example
+ * Normal event
+ * event | | | |
+ * time ----------------
+ * callback | | | |
+ *
+ * Throttled event [300ms]
+ * event | | | |
+ * time ----------------
+ * callback | | |
+ * [300] [300]
+ */
+
+export function throttle<T extends []>(
+ func: (..._: T) => unknown,
+ limit: number,
+): (..._: T) => void {
+ let lastTimeoutId;
+ let lastCallTime: number;
+
+ return function throttled(...args) {
+ const nextCall = () => {
+ func.apply(this, args);
+ lastCallTime = Date.now();
+ };
+
+ if (!lastCallTime) {
+ nextCall();
+ } else {
+ clearTimeout(lastTimeoutId);
+ const timeBetweenCalls = Date.now() - lastCallTime;
+ const waitTime = Math.max(0, limit - timeBetweenCalls);
+ lastTimeoutId = setTimeout(() => {
+ if (timeBetweenCalls >= limit) {
+ nextCall();
+ }
+ }, waitTime);
+ }
+ };
+}