Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created November 20, 2020 10:52
Show Gist options
  • Save bartwttewaall/369948bc254807868a24856a2a19e773 to your computer and use it in GitHub Desktop.
Save bartwttewaall/369948bc254807868a24856a2a19e773 to your computer and use it in GitHub Desktop.
Debounce function with jsdoc and example
/**
* Debounce function that, as long as it continues to be invoked, will not be triggered.
* @param {Function} func - Function to be debounced
* @param {number} wait - Time in milliseconds to wait before the function gets called.
* @param {boolean} [immediate] - Optional immediate flag, if passed, trigger the function on the leading edge, instead of the trailing.
* @returns {Function}
* @example
window.addEventListener('resize', debounce((evt) => console.log(evt), 250));
*/
export function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment