Created
March 10, 2022 03:45
-
-
Save wteja/2e0ed709fc41533fe193a5f2d4a9c700 to your computer and use it in GitHub Desktop.
JavaScript Debounce Function
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
function debounce(callback, timeout = 500) { | |
let timer; | |
return (...args) => { | |
clearTimeout(timer); | |
timer = setTimeout(() => { | |
callback.apply(callback, args); | |
}, timeout); | |
}; | |
} | |
/** Sample usage **/ | |
// Create log function that log the value from HTML Input. | |
function logInput(e) { | |
console.log(e.target.value); | |
} | |
// Create function that wrapped with debounce. | |
const captureInput = debounce(logInput, 1000); | |
// Finding HTML Input in HTML Document. | |
const input = document.getElementById("myinput"); | |
// Add event listener for onChange event. then it will pass event argument as parameter to debounce function. | |
input.addEventListener('change', captureInput); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment