1

I want to use an implementation of debounce for a basic search feature :

const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

The idea is to create a timeout during which the multiple user keyups supposed to trigger a query will be delayed, so that the query only happen once and I don't overload the server.

I am then using it like this on keyup event :

  Array.from(searchFields).forEach(searchField =>
    searchField.addEventListener(
      "keyup",
       () => debounce(searchPrograms, 1000)(searchField)
    )
  )

Where searchProgram is a function that performs the request to the server.

There's indeed a delay of 1000ms before searchPrograms is executed, however searchPrograms is then executed as many times as there was keyup, which is not the expected behavior... It should only execute once.

What am I doing wrong here ?

David Geismar
  • 3,152
  • 6
  • 41
  • 80

0 Answers0