Skip to content

Instantly share code, notes, and snippets.

@devethan
Last active September 24, 2023 05:36
Show Gist options
  • Save devethan/b50134db72da5287c7038316f1e5e1ef to your computer and use it in GitHub Desktop.
Save devethan/b50134db72da5287c7038316f1e5e1ef to your computer and use it in GitHub Desktop.
How to apply delay on your event
import { useRef, useEffect } from "react";
/**
* debounce: Ensuring that only the last event gets executed after the delay
* throttle: Ensuring that only the first event gets executed and subsequent events within the delay period are ignored.
*/
type DelayType = "debounce" | "throttle";
/**
* The hook is designed to provide a delayed execution of a callback function based on either a debounce or throttle mechanism.
* This is a useful utility for various scenarios, such as delaying search input or button clicks.
*
*/
const useDelay = (type: DelayType, delay: number) => {
const ref = useRef<ReturnType<typeof setTimeout>>();
if (Number.isNaN(delay) || delay <= 0) {
throw new Error(`Invalid delay: ${delay}`);
}
useEffect(() => {
return () => {
if (ref.current) {
clearTimeout(ref.current);
}
};
}, []);
return function (callback: () => void) {
switch (type) {
case "debounce":
// Clears any existing timeout
clearTimeout(ref.current!);
break;
case "throttle":
// Ignore current execution, if there is an event during the period
if (ref.current) {
return;
}
break;
default:
throw new Error(`Cannot resolve the given type: ${type}`);
}
// Apply given delay
ref.current = setTimeout(() => {
callback();
ref.current = undefined;
}, delay);
};
};
export default useDelay;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment