Reputation: 1
I write a debounce function and want to display input using that function.
let btn = document.querySelector('.firstScreen')
let input = document.querySelector('input')
function debounce(fn, time) {
let timer = null
return function(...args){
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn()
}, time)
}
}
function display(){
btn.children[1].innerHTML=input.value
}
it is not working when I write like this:
document.addEventListener('keyup',function(){
debounce(display, 2000)
})
but working like this:
document.addEventListener('keyup',debounce(display, 2000))
why?
Upvotes: 0
Views: 46
Reputation: 177851
You return a function from the debounce(display, 2000)
as you should. That function is not callable as a function so the first example is not using the returned function but only creating the function you are supposed to use
You COULD do
document.addEventListener('keyup',function(){ return debounce(display, 2000) })
which is a waste of code when you can do what you already determined works
document.addEventListener('keyup',debounce(display, 2000))
Upvotes: 1