Skip to content

Instantly share code, notes, and snippets.

@wteja
Created March 10, 2022 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wteja/2e0ed709fc41533fe193a5f2d4a9c700 to your computer and use it in GitHub Desktop.
Save wteja/2e0ed709fc41533fe193a5f2d4a9c700 to your computer and use it in GitHub Desktop.
JavaScript Debounce Function
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