Debounce is a advance version of controlling intervals of running a function!
suppose we’re calling an API on entering each letter in input box for suggestions, this is very tempting and costly also, here comes debounce to set intervals let say we’ll call API only after using stopped typing for certain time lets says for 1s!
For example :
const input = document.getElementById("input");
const def = document.getElementById("default");
const deb = document.getElementById("debounce");
const debUpdate = debounce((text) => {
deb.textContent = text;
}, 5000); //The change will occure after 5 seconds!
input.addEventListener("input", (e) => {
def.textContent = e.target.value;
debUpdate(e.target.value);
});
function debounce(cb, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
cb(...args);
}, delay);
};
}
JavaScript
Reference :


