Search code examples
javascriptjquerylodash

Conditional debounce, depending on event.keyCode


I have a search field that takes user input and makes ajax requests using a debounced event listener.

html:

<input id="search" type="text"></input>

javascript:

function makeRequest() {
  // make ajax request, do things with the information
}

$('#search').on('keypress', _.debounce(makeRequest, 200));

I need the event listener to not use the debounced ajax function on arrow up and down, that is event.keyCode === 38 or event.keyCode === 40

Is there a way to apply the advice from this question to my problem?


Solution

  • The problem was that the callback to the event listener needs to call the function returned from _.debounce, not just create the debounced function.

    $('#search').on('keypress', function(event) {
      if (event.which === 38 || event.which === 40) {
        // do other things
        return;
      }
      _.debounce(makeRequest, 200)();
    });