diff options
| author | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
|---|---|---|
| committer | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
| commit | bce557cc2dc767628bed6aac87301a1be7c5431b (patch) | |
| tree | b51a051228d01fe3306cd7626d4a96768aadb944 /shared/components/src/utils/debounce.ts | |
init commit
Diffstat (limited to 'shared/components/src/utils/debounce.ts')
| -rw-r--r-- | shared/components/src/utils/debounce.ts | 40 |
1 files changed, 40 insertions, 0 deletions
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<F>) => void + */ +export function debounce<F extends (...args: any[]) => any>( + fn: F, + delayMs: number, + immediate = false, +): (...args: Parameters<F>) => 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; |
