1

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!

codeMike
  • 65
  • 7
  • 1
    The event listener is the function _returned_ from `debounce`. So it will have closure around `timer` – Nick Jan 12 '23 at 04:39
  • @Nick So is it like: when the eventlistener was first added, debounce was called -> return the function inside. And after this, everytime the event fired, the **same** returned function gets called? – codeMike Jan 12 '23 at 04:40
  • 1
    Correct, the same returned function is called – Nick Jan 12 '23 at 04:41
  • Every time a function is called, the variables declared inside are initialized again, in a separate variable environment. It's not that different from an argument. `foo(2); foo(4)` results in two calls of `foo` with two different values for the argument. Similarly, calling `debounce` twice results in two different calls, where each call has its own independent binding for that `timer` local variable inside the closure. – CertainPerformance Jan 12 '23 at 04:42
  • @CertainPerformance So in this case, I only have one eventlistener that uses debounce, which means debounce gets called once. But its returned function inside the closure gets called everytime the event triggers, so I guess the `timer` variable gets shared everytime since each call of the inside function belong to the same closure? Is this correct? – codeMike Jan 12 '23 at 04:47
  • 1
    Yes, the one call of `debounce` results in only one binding for `timer`, that the one returned function references every time it's called – CertainPerformance Jan 12 '23 at 04:49

0 Answers0