Skip to content

Instantly share code, notes, and snippets.

@iansan5653
Created June 14, 2019 18:07
Show Gist options
  • Save iansan5653/e7e4f66c631480ce10f6ec7fbb08e1e8 to your computer and use it in GitHub Desktop.
Save iansan5653/e7e4f66c631480ce10f6ec7fbb08e1e8 to your computer and use it in GitHub Desktop.
Debounce a function in JavaScript
/**
* Either returns a function that won't execute until it hasn't been called for
* `delay` milliseconds, or returns a function that will execute immediately but
* not again until it hasn't been called in `delay` milliseconds.
* @param {function(...any)} func The function to execute only once.
* @param {number} delay Number of milliseconds to wait after the last call
* before executing the function.
* @param {boolean} immediate If true, will execute immediately rather than
* waiting, but won't execute again until it hasn't been called in `delay` ms.
* @return {function(...any)} A function that, when called, will execute `func`
* according to the above behavior.
*/
function debounce(func, delay, immediate = false) {
let debounceTimeoutId = null;
return function (...args) {
if (immediate && debounceTimeoutId === null) {
func(...args);
}
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => {
if (!immediate) {
func(...args);
}
debounceTimeoutId = null;
}, delay);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment