Skip to content
Advertisement

delay JavaScript on input, so function does fire for each character inputted into a search field

I have a search field to allow users to filter the results that are returned from the database. I have it set so that the search field has a .on('input', function() { which will trigger another function.

This poses a problem in which if a user was to search for “crumble” the ajax request will be triggered for each character the user types in.

Is there a way to delay the JavaScript so that if the user is searching for a product, the function isn’t fired for each character inputted, but will trigger when detected that the user hasn’t typed something further in. I.E. when the user is done typing in what that are searching.

Code:

$(document).ready(function () {
  $('#cards-search').on('input', function() {
    cards_page = ''
    cards_search = this.value;
    get_card_data()
  });
});

Advertisement

Answer

Following VLAZ advice I looked into debouncing and it is exactly what I needed.

I followed the steps here

HTML:

<input type="search" id="cards-search" onkeyup="cardSearchChange()"...

Javascript:

function debounce(func, timeout = 250){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

function card_search() {
  cards_page = '';
  cards_search =  document.getElementById('cards-search').value;
  get_card_data();
}
cardSearchChange = debounce(() => card_search());
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement