Created
August 25, 2024 21:22
-
-
Save jrrio/090476535904d5f730a27c1630654781 to your computer and use it in GitHub Desktop.
Debounce is used to limit the number of times a function is called in a short period of time.
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 is used to limit the number of times a function is called in a short period of time. | |
* @param {Function} func | |
* @param {Number} wait - a delay in milliseconds, usually 250 ms by default. | |
* @returns {Function} a new function that will delay the execution of the original function. | |
*/ | |
const debounce = (func, wait = 250) => { | |
let timeout; | |
return function (event) { | |
// console.log(`debounced ${func.name} called`) | |
clearTimeout(timeout); | |
timeout = setTimeout(() => func(event), wait); | |
}; | |
}; | |
/****************************************************** | |
* | |
* Using debounce() in a search input | |
* Example: <https://codepen.io/jrrio/pen/dNKLMR> | |
* | |
*****************************************************/ | |
const enableBtnShowModal = () => { | |
// ... | |
}; | |
const search = () => { | |
// ... | |
}; | |
document.addEventListener("DOMContentLoaded", function () { | |
const input = document.getElementById("search"); | |
/* Events occur in a sequence, for instance: | |
keydown > keypress (deprecated) > input > keyup | |
*/ | |
if (input) { | |
input.addEventListener("input", debounce(enableBtnShowModal)); | |
input.addEventListener("keyup", debounce(search)); | |
input.focus(); | |
} | |
// ... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment