Skip to content

Instantly share code, notes, and snippets.

@maninak
Created May 3, 2018 13:43
Show Gist options
  • Save maninak/75b7178ecab9b42f53d088c4a8c69390 to your computer and use it in GitHub Desktop.
Save maninak/75b7178ecab9b42f53d088c4a8c69390 to your computer and use it in GitHub Desktop.
/**
* Debounces (postpones) executing `func` until _at least_ `msWait` seconds have elapsed
* since the last time the same function had again been requested to execute.
*
* Example:
* const repaintElem = setRandomBgColorToElem(elem);
* document.addEventListener('resize', debounce(repaintElem, 10, true));
*
* @param {function} func The function to be debounced
* @param {number} [msWait=50] The minimum amount of time in miliseconds to wait before executing `func`
* @param {boolean} [execAsap=false] Whether the function should be called immediately the first time
*
* @returns {function} The function provided, debounced by the time provided in milliseconds
*/
export default (func, msWait = 50, execAsap = false) => {
let timeout;
return function debounced (...args) {
function delayed () {
if (!execAsap) {
Reflect.apply(func, this, args);
}
timeout = undefined;
}
if (timeout) {
clearTimeout(timeout);
} else if (execAsap) {
Reflect.apply(func, this, args);
}
timeout = setTimeout(delayed, msWait);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment