Following is my code implementation for which debounce in JavaScript is not working. I am trying to execute the function only after 3 sec delay. Let me know what I am doing wrong here.
Code -
function debounce(fn, delay) {
let timeout;
return function() {
if(timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(fn, delay);
}
}
const myinp = document.getElementById('myinp');
if(myinp) {
myinp.addEventListener('input', function(e) {
console.log(`Console Value =>`, e.target.value)
debounce(function() {
console.log(`++++`) // This console is not working
}, 3000)
})
}
<input type="text" id="myinp" />
Note that in your example,
debounce()returns an anonymous function, which is then not called anywhere.Slightly modified example below (but using .apply() to assign the appropriate
this):