0

I've got a jQuery function to search through table rows. Currently I've got about 2000+ rows but it's only going to grow. Even when I click the input tag the browser freezes and then searching through all the rows is just a pain. This is the code I use:

$(".filter-input").each(function() {
  var $filter = $(this);
  $filter.on("change keydown keyup keypress", function() {
    setTimeout(function() {
      var $tbodies = $searchtable.find("tbody");
      var value = $filter.val();

      $tbodies.each(function() {
        var $tbody = $(this);
        if (filterfunction($tbody, value))
          $tbody.show();
        else
          $tbody.hide();
      });
    }, 1);
  });
});

The .filter-input is the input tag here.

On my high end PC i don't really face this issue, but the problem is very prevalent on average devices. So my question is how do I optimize this code or even better what is the best way to search through a lot of rows in JS.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bigya Tuladhar
  • 69
  • 1
  • 12
  • https://css-tricks.com/debouncing-throttling-explained-examples/ – Mosh Feu Nov 23 '20 at 09:03
  • Depends on what `filterfunction` does and how you want to "search" – freedomn-m Nov 23 '20 at 11:27
  • 1
    Def apply a debounce, otherwise you run the search for every keypress. You may also want to require say 3 characters before starting the search - its not good UX to give the user more hits than they can usefully consume. The most optimal way to search is with the minimal data. Can you keep, or create from the table, a separate data structure for that purpose? If so, don't include any columns that are not applicable for the search. Once you have a dedicated structure for searching you can really go to town over indexing approaches - see Mr Google for that. – Vanquished Wombat Nov 23 '20 at 23:03
  • Oh alright , i'll make a min character requirement. Also I tired _.debounce() from underscore.js. but I'm confused where actual to implement that in the code above. do I keypress events? I tried that and all i got are errors. I might need look at some more documentations. – Bigya Tuladhar Nov 24 '20 at 09:21
  • SO is your friend on that too...https://stackoverflow.com/questions/13158708/using-underscores-debounce-method/13158852 – Vanquished Wombat Nov 24 '20 at 11:38

0 Answers0