Adding Debounce to the Typeahead

One of the ways to determine the quality of code is to see how resilient the code is to change.

Let’s see how the vanilla snippet fares when adding debouncing:

 let​ latestQuery;
 searchBar.addEventListener(​'keyup'​, debounce(event => {
 let​ searchVal = latestQuery = event.target.value;
  fetch(endpoint + searchVal)
  .then(results => {
 if​ (searchVal === latestQuery) {
  updatePage(results);
  }
  });
 }));

Not much of a change, though it’s easy to miss the fact that the event function is debounced, which may lead to confusion if someone inherits the project. One could extract the inner function into a separate variable, adding more code but enhancing clarity. On the other hand, how does the Rx version do? ...

Get Build Reactive Websites with RxJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.