Skip to content

Instantly share code, notes, and snippets.

@lski
Created June 11, 2020 10:51
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 lski/65f2daa7d0c45ddc6ed2d910e21330c3 to your computer and use it in GitHub Desktop.
Save lski/65f2daa7d0c45ddc6ed2d910e21330c3 to your computer and use it in GitHub Desktop.
A simple debounce higher order function
/**
* Creates a new function that will run the callback a maximum of once at the end of the timeout period.
* Useful for using with event listeners that fire often. The opposite of throttling.
*
* @param delay The length of time in ms before firing the callbcak
* @param callback The callback to fire once the time has passed
*/
export function debounce(delay, callback) {
let _args;
let _running = false;
return (...args) => {
_args = args;
if (_running) {
return;
}
_running = true;
setTimeout(() => {
// Allow another timeout to be created as this will be fired
_running = false;
// Now call the callback with the last args stored
callback(..._args);
}, delay);
};
}
/**
* Creates a new function that will run the callback a maximum of once at the end of the timeout period.
* Useful for using with event listeners that fire often. The opposite of throttling.
*
* @param delay The length of time in ms before firing the callbcak
* @param callback The callback to fire once the time has passed
*/
export function debounce(delay, callback) {
let _args;
let _running = false;
return (...args) => {
_args = args;
if (_running) {
return;
}
_running = true;
setTimeout(() => {
// Allow another timeout to be created as this will be fired
_running = false;
// Now call the callback with the last args stored
callback(..._args);
}, delay);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment