Skip to content

Instantly share code, notes, and snippets.

@SynCap
Created June 30, 2021 04:41
Show Gist options
  • Save SynCap/229a361c8a27d49b7b8cde285c5614f3 to your computer and use it in GitHub Desktop.
Save SynCap/229a361c8a27d49b7b8cde285c5614f3 to your computer and use it in GitHub Desktop.
Debounce & Throttle functions – Javascript
/**
* Debounce - delay the run of the functions (spread in time of all calls)
*
* @param {<type>} func The function
* @param {<type>} delay The delay
* @return {<type>} { description_of_the_return_value }
* @example
debouncedBtn.addEventListener(
'click',
debounce(function() {
console.info('Hey! It is', new Date().toUTCString());
}, 3000)
);
*
*/
const debounce = (func, delay) => {
let inDebounce;
return function() {
const context = this;
const args = arguments;
clearTimeout(inDebounce);
inDebounce = setTimeout(() => func.apply(context, args), delay);
};
};
/**
* Throttle - cut the amount of calls of functions in a period (denoise, waitress)
*
* @param {<type>} func The function
* @param {<type>} limit The limit
* @return {<type>} { description_of_the_return_value }
* @example
throttleBtn.addEventListener(
'click',
throttle(function() {
return console.log('Hey! It is', new Date().toUTCString());
}, 1000)
);
*/
const throttle = (func, limit) => {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment