Created
November 20, 2020 10:52
-
-
Save bartwttewaall/369948bc254807868a24856a2a19e773 to your computer and use it in GitHub Desktop.
Debounce function with jsdoc and example
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
/** | |
* 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