Search code examples
javascriptlodash

Can't explain why `_.debounce` works in this way?


I use lodash debounce to prevent users press keyboard twice in a very short of time. Below is the code which doesn't work:

window.addEventListener('keydown', _.debounce((e) => this.keyDown(e), 300), false);

But it works if I change to:

window.addEventListener('keydown', this.debounceKeyFunc.bind(this), false);
debounceKeyFunc = _.debounce((e) => this.keyDown(e), 300);

debounceKeyFunc is a method of the instance of the current class as this.debounceKeyFunc.

I don't understand why I need to define a separate function to debounce the key event callback in order to make it work.


Solution

  • -- edit -- Actually, what I wrote is true but doesn't apply here. debounce is only called once when the handle is registered and should work. The first also does work for me, except for the face that this is not defined

    -- edit --

    You have to ensure the debounced function is only created once, because it holds an internal state that is used for the debouncing, remembering when it was last called.

    In your first example, the debounced function is created on every event, meaning debouncing starts anew every time, meaning there is nothing to debounce because every event get's it's own debouncing.

    I hope that explains it, otherwise just ask.