Skip to content

Instantly share code, notes, and snippets.

@lon-io
Created July 3, 2018 17:41
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 lon-io/a56b620f3e65bb0d56ea9c8236ca0a1d to your computer and use it in GitHub Desktop.
Save lon-io/a56b620f3e65bb0d56ea9c8236ca0a1d to your computer and use it in GitHub Desktop.
A Javascript function to Debounce other functions
// Debounce function
let debounce = (func, delay) => {
let timeout;
return (...args) => {
// If this function is called again, and there's a timeout defined, clear it;
if (timeout) clearTimeout(timeout);
// Set a timeout to call the original function, after the `delay`
timeout = setTimeout(() => {
func(...args);
}, delay);
};
};
// Test
let log = (...args) => {
console.log(...args);
}
let debouncedLog = debounce(log, 3000);
debouncedLog('I won\'t run');
setTimeout(() => {
debouncedLog('I will run! oh wait! :(');
}, 2000);
debouncedLog('I won\'t run either');
setTimeout(() => {
debouncedLog('I should run, but won\'t');
debouncedLog('Yaay!', 'I will defo. run');
}, 4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment