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 is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".
I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.
Is there a best practice for something like this?
$('#searchString').keypress(function(e) {
if (e.keyCode == 13) {
var url = '/Tracker/Search/' + $("#searchString").val();
$.get(url, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
else {
var existingString = $("#searchString").val();
if (existingString.length > 2) {
var url = '/Tracker/Search/' + existingString;
$.get(url, function(data) {
$('div#results').html(data);
$('#results').show();
});
}
}
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/
You can do something like this:
What this does is perform a search (on
keyup
, better thankeypress
for these situations) after500ms
by storing a timer on the#searchString
element's.data()
collection. Everykeyup
it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another500ms
timeout before auto-searching.