Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Last active April 18, 2022 00:32
Show Gist options
  • Save MarekZeman91/094d1e95e57583d6537e81bfb2a1fd70 to your computer and use it in GitHub Desktop.
Save MarekZeman91/094d1e95e57583d6537e81bfb2a1fd70 to your computer and use it in GitHub Desktop.
import { useMemo, useRef } from 'react';
import { useScope } from './useScope';
export type UseThrottlerCallback = (...args: any[]) => void;
export const useThrottler = <T extends UseThrottlerCallback>(callback: T, delay: number): T & { clear: () => void } => {
const scope = useScope({ callback, delay });
const timeout = useRef<number>(0);
return useMemo(() => {
const throttler = (...args: T[]) => {
if (!timeout.current) scope.callback(...args);
window.clearTimeout(timeout.current);
timeout.current = window.setTimeout(() => (timeout.current = 0), scope.delay);
};
throttler.clear = () => window.clearTimeout(timeout.current);
return throttler as T & { clear: () => void };
}, [scope]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment