Skip to content

Instantly share code, notes, and snippets.

@jgoslow
Created August 13, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgoslow/cf092a2f2b9ac093cc4486348b473363 to your computer and use it in GitHub Desktop.
Save jgoslow/cf092a2f2b9ac093cc4486348b473363 to your computer and use it in GitHub Desktop.
Throttle and Debounce JS Functions
/**
* Debounce Function
* to reduce # of events fired
* example: Scroll listeners
*/
function debounce(callback, interval) {
let debounceTimeoutId;
return function(...args) {
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => callback.apply(this, args), interval);
};
}
/**
* Throttling Function
* to reduce # of events fired
* example: Scroll listeners
*/
function throttle(callback, interval) {
let enableCall = true;
return function(...args) {
if (!enableCall) return;
enableCall = false;
callback.apply(this, args);
setTimeout(() => enableCall = true, interval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment