Created
June 14, 2019 18:07
-
-
Save iansan5653/e7e4f66c631480ce10f6ec7fbb08e1e8 to your computer and use it in GitHub Desktop.
Debounce a function in JavaScript
This file contains hidden or 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
/** | |
* 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