Skip to content

Instantly share code, notes, and snippets.

@abelflopes
Created August 22, 2022 20:51
Show Gist options
  • Save abelflopes/ff19310a793a36b572991a4fd1a1cbed to your computer and use it in GitHub Desktop.
Save abelflopes/ff19310a793a36b572991a4fd1a1cbed to your computer and use it in GitHub Desktop.
Typescript debounce
type TimeOutSheet = Record<string, ReturnType<typeof setTimeout | typeof clearTimeout>>;
const timeOutSheet: TimeOutSheet = {};
const getFnId = (fn: () => unknown): string => {
return [fn.name, fn.toString()].join("").split(" ").join("");
};
export const debounce = (callback: () => void, ms: number): void => {
const toId = timeOutSheet[getFnId(callback)];
if (toId) clearTimeout(toId);
const id = setTimeout(callback, ms);
timeOutSheet[getFnId(callback)] = id;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment