optimized search using ajax and keypress
- by ooo
i have the following code as i want to search a database as a user is typing into a textbox. This 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 practices 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();
});
}
}