Created
May 3, 2018 13:43
-
-
Save maninak/75b7178ecab9b42f53d088c4a8c69390 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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