I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user i
See this older question:
How do I make my live jQuery search wait a second before performing the search?
What I would do is each key press use a setTimeout function with the desired delay. So that function will fire after that timeout. Each key press then delete the timer and set a new one, with clearTimeout();
See here for some examples, scrolling past all the adverts.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
I just want to add some more points to the question. Throttling and debounce concepts are related to this topics.
Throttling : It will make you to execute the function in a specified interval.
Debounce : It will make you to execute the function when user has stopped typing.
You can achieve this two by setimeout , cleartimeout functions.Check this link will give you a clear walk-through of it.
LINK
You can do something like this:
$('#searchString').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13)
search(true);
else
$(this).data('timer', setTimeout(search, 500));
});
function search(force) {
var existingString = $("#searchString").val();
if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char
$.get('/Tracker/Search/' + existingString, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
What this does is perform a search (on keyup
, better than keypress
for these situations) after 500ms
by storing a timer on the #searchString
element's .data() collection. Every keyup
it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500ms
timeout before auto-searching.