From bce557cc2dc767628bed6aac87301a1be7c5431b Mon Sep 17 00:00:00 2001 From: rxliuli Date: Tue, 4 Nov 2025 05:03:50 +0800 Subject: init commit --- shared/components/src/utils/debounce.ts | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 shared/components/src/utils/debounce.ts (limited to 'shared/components/src/utils/debounce.ts') diff --git a/shared/components/src/utils/debounce.ts b/shared/components/src/utils/debounce.ts new file mode 100644 index 0000000..fcadbef --- /dev/null +++ b/shared/components/src/utils/debounce.ts @@ -0,0 +1,40 @@ +/* eslint-disable import/prefer-default-export */ + +/** + * @name debounce + * @description + * Creates a debounced function that delays invoking func until + * after delayMs milliseconds have elapsed since the last time the + * debounced function was invoked. + * + * @param delayMs - delay in milliseconds + * @param immediate - Specify invoking on the leading edge of the timeout + * (Defaults to trailing) + * + *(f: F): (...args: Parameters) => void + */ +export function debounce any>( + fn: F, + delayMs: number, + immediate = false, +): (...args: Parameters) => void { + let timerId; + + return function debounced(...args) { + const shouldCallNow = immediate && !timerId; + clearTimeout(timerId); + + if (shouldCallNow) { + fn.apply(this, args); + } + + timerId = setTimeout(() => { + timerId = null; + if (!immediate) { + fn.apply(this, args); + } + }, delayMs); + }; +} + +export const DEFAULT_MOUSE_OVER_DELAY = 300; -- cgit v1.2.3