1

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()
  });
});

Ross
  • 2,463
  • 5
  • 35
  • 91
  • 3
    Look into debouncing - this is the standard approach in these cases. In fact, seaching on input is the go-to example of when debouncing is useful. – VLAZ Jul 07 '22 at 06:01
  • @VLAZ Thank you, that is exactly what I needed. The top result on google gave me the code needed. – Ross Jul 07 '22 at 06:21

3 Answers3

0

try this, this is called debouncing in case u need to search more about it

$(document).ready(function () {
    let oldTimeout = null;
    let timeToWaitBeforeSending = 1000 //ms
    $('#cards-search').on('input', function () {
        if (oldTimeout !== null) {
            clearTimeout(oldTimeout);
        }
        timout = setTimeout(() => {
            cards_page = '';
            cards_search = this.value;
            get_card_data();
        }, timeToWaitBeforeSending );
    });
});
0

// Run javascript function when user finishes typing instead of on key up?

            var typingTimer;                
            var doneTypingInterval = 5000;  

            //on keyup, start the countdown
             $('#cards-search').on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
            });

            //on keydown, clear the countdown 
             $('#cards-search').on('keydown', function () {
            clearTimeout(typingTimer);
            });

            //user is "finished typing," do something
            function doneTyping () {
            //do something

                console.log("DOne");
            }
0

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());
Ross
  • 2,463
  • 5
  • 35
  • 91