Skip to content

Instantly share code, notes, and snippets.

@davidkayce
Created July 13, 2021 14:33
Show Gist options
  • Save davidkayce/b37e84c1f85683cf7fded91bb8bdeb41 to your computer and use it in GitHub Desktop.
Save davidkayce/b37e84c1f85683cf7fded91bb8bdeb41 to your computer and use it in GitHub Desktop.
// Debounce: Debouncing enforces that a function not be called again until
// a certain amount of time has passed without it being called
// use:
// If we want to debounce an add function: const add = (a, b) => a + b;
// resulting debounce is debounce(add, 500)(2,3);
// this would give 5 only after 500ms of no input
export const debounce = (func, wait) => {
let timeout;
return (...args) => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};
// Throttle: The throttle function is a cousin of the debounce
// but throttling enforces a maximum number of times a function can
// be called over time.As in "execute this function at most once every 100 milliseconds.
// The use is similar to the debounce function
export const throttle = (func, interval) => {
let shouldCall;
return (...args) => {
if (shouldCall) {
func(...args);
shouldCall = false;
setTimeout(() => {
shouldCall = true;
}, interval); // set the next time the function can be called
}
return false;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment