I have a function that is supposed to debounce another function so that you have to wait 500ms before the function supposedly re-executes. The problem is, I think the function re-executes the same number of times (many times), just 500ms later, because there is the same number of console logs in my example below.
I have tried to build a simple example to demonstrate this
let debounce = (func, wait) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
let test = () => console.log('test');
let debouncedTest = debounce(test, 500);
let inputField = document.getElementById('test')
inputField.addEventListener("input", debouncedTest);
<input type='text' id='test' />
So to clarify, what should happen is if you type, for example, 'abc' into the input field all in under 500ms, it should only execute once (500ms after the last type), but instead it seems to execute 3 times.
How can I get this to only run once after the 500ms delay rather than the number of times you type into the box? I assume there is literally no point in using a debounce function if it just executes the same number of times anyway as presumably it would not improve performance at all. Thanks for any help here.