Reputation: 301
I'm using Kendo UI for grid displays of a bunch of data out of a database. Attached to this grid, I have a search bar. Right now, the following code searches the grid for input types into the search bar:
searchBar = $("#search");
searchBar.keyup(() => {
const term = searchBar[0].value;
searchGrid(term, "#Grid", filters);
});
How searchGrid
works isn't important. What is important here is the fact that the event is binded to a keyup
: as the user types, I want the grids to filter immediately. I don't want them to type in their selection and then press a button to search - that's not my use case. I need it to automatically filter as they type.
That being said, that's where my issues come from. On a grid with a regular amount of data stored within it, this is no problem. It works great. However, on the specific grid that I'm currently working in, there's over 1000 entries. Since the search is binded via a keyup
, it gets really slow as it tries to filter through thousands of times. I've been told I could improve this a lot if I utilized debouncing to stall the search for about 200ms while a user types, rather than firing it on every single letter change. The only problem is, I can't seem to get the debounce to work at all. Here's the debounce function I pasted into my codebase:
function debounced(delay, fn) {
let timerId;
return function (...args) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn(...args);
timerId = null;
}, delay);
}
}
And here are some ways that I tried to use the debounce function in conjunction with the snippet I provided earlier to stall the search, none of which worked:
searchBar = $("#search");
searchBar.keyup(() => {
const term = searchBar[0].value;
debounced(200, searchGrid(term, "#Grid", filters));
});
searchBar = $("#search");
searchBar.keyup( () => debounced(200, searchGrid(searchBar[0].value, "#Grid", filters)));
These just filtered the grid normally, and didn't behave any differently than the first snippet I provided. So, obviously, the debounce didn't happen at all. I tried removing the arrow function entirely and just passing in the debounced function into the keyup, and got this new error:
Uncaught TypeError: fn is not a function
So I'm at a bit of a loss as to how to use debouncing. Any help would be appreciated.
Upvotes: 0
Views: 2132
Reputation: 27508
I have used this code in previous projects
var timeout;
var delay = 500; // 100 ms
$('#searchTerm').keyup(function(e) {
if(timeout) clearTimeout(timeout);
timeout = setTimeout(function() { performSearch(); }, delay);
});
function performSearch() {
var panelbar, filter, searchRegEx, $span;
filter = $("#searchTerm").val();
if (filter == lastFilter) return;
if (filter.length < 3) return; // only search 3 or more characters in searchTerm
… the rest is unimportant …
lastFilter = filter;
}
Upvotes: 3