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" />
CodePudding user response:
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
):
function debounce(fn, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
const myinp = document.getElementById('myinp');
if (myinp) {
myinp.addEventListener('input', debounce(function(e) {
console.log(` `)
}, 3000))
}
<input type="text" id="myinp" />
CodePudding user response:
Not sure why Oleg went for such a long answer (even showing the global anti-pattern). All you needed to do is use your debounce
function API properly. That is, have a reference to the debounced
function and call it in your event listener.
function debounce(fn, delay) {
let timeout;
return function() {
if(timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(fn, delay);
}
}
const myinp = document.getElementById('myinp');
if(myinp) {
const debounced = debounce(function() {
console.log(` `) // This console is now working
}, 3000)
myinp.addEventListener('input', function(e) {
console.log(`Console Value =>`, e.target.value)
debounced();
})
}
<input type="text" id="myinp" />