I created a debounce function here is the code:
function debounce(func, timeout = 300) {
let timer;
return (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
Now I am using this in an onChange event for a search bar.
search.addEventListener("input", (e) => {
eventCount++;
eventOutput.textContent = eventCount;
debounce(() => {
apiRequestCount++;
apiCount.textContent = apiRequestCount;
}, 200);
});
but this is not working, but when I use the following code it works.
const debouncedFunction = debounce(() => {
apiRequestCount++;
apiCount.textContent = apiRequestCount;
}, 200);
search.addEventListener("input", (e) => {
eventCount++;
eventOutput.textContent = eventCount;
debouncedFunction();
});
I am not able to figure out why it is behaving like this both are almost the same, in the second one I have only stored the debounce function in a const.
The debounce function returns another function, which you can think of like an object of a class (it has a "memory" of timer, which is setTimeout id), and you always invoke the same function created with debounce() function. But in the first example, you create new debounced function on every input event, which creates new object unaware of previous timeouts.