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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.