mirror of
https://github.com/jnsahaj/tweakcn.git
synced 2026-08-28 23:02:07 +08:00
20 lines
453 B
TypeScript
20 lines
453 B
TypeScript
export function debounce<T extends (...args: any[]) => void>(
|
|
fn: T,
|
|
delay: number
|
|
): T & { cancel: () => void } {
|
|
let timeoutId: NodeJS.Timeout;
|
|
|
|
const debounced = function (this: unknown, ...args: Parameters<T>) {
|
|
clearTimeout(timeoutId);
|
|
timeoutId = setTimeout(() => {
|
|
fn.apply(this, args);
|
|
}, delay);
|
|
} as T & { cancel: () => void };
|
|
|
|
debounced.cancel = () => {
|
|
clearTimeout(timeoutId);
|
|
};
|
|
|
|
return debounced;
|
|
}
|