I'm looking at this simple piece of debounce code:
function debounce(event, wait) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
event.apply(this, args)
}, wait)
}
}
And suppose we use it in an eventListener
window.addEventListener('resize', debounce(handler, 200))
Now what I find confusing is that if the resize
event gets fired multiple times, how does the timer
inside debounce gets persisted between the calls? The reason I say it gets persisted is that if the same event is triggered within the delay
, the timer
is
supposed to be cleared. But since it can be cleared, that means it gets persisted between multiple calls?
Shouldn't it be every time the resize function is fired, we call debounce
once, and it will give us a new "closure"?
I think I might have some misunderstanding with how eventlistener handle its callback function, so please shine some light on this!