Skip to content

Instantly share code, notes, and snippets.

@ExcitedSpider
Created February 20, 2021 06:17
Show Gist options
  • Save ExcitedSpider/3c201df72397cf8f9cfba059f6a9051c to your computer and use it in GitHub Desktop.
Save ExcitedSpider/3c201df72397cf8f9cfba059f6a9051c to your computer and use it in GitHub Desktop.
simple debounce & throttle
export const debounce: <T extends []>(fn: (...args: T) => void, wait: number) => (...args: T) => void = (fn, wait) => {
let timeout = -1;
return (...args) => {
if (timeout !== -1) clearTimeout(timeout);
timeout = setTimeout(() => {
fn(...args);
}, wait);
};
};
export const throttle: <T extends []>(fn: (...args: T) => void, wait: number) => (...args: T) => void = (fn, wait) => {
let canRun = true;
return (...args) => {
if (!canRun) {
return;
}
fn(...args);
canRun = false;
setTimeout(() => {
canRun = true;
}, wait);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment