I would like to throttle the following ajax live search function I wrote.
I made it so that requests are only sent if a minimum of 2 characters are entered. I also want to throttle the ajax for a quarter of a second to give the user a chance to type what they want. I wrapped the ajax in a setTimeout function, but that didn't work.
$('#search').keyup(function() {
var string = $(this).val();
if (string.length >= 2) {
$.ajax({
'type': 'GET',
dataType: 'html',
'url': url,
'success': function(data){
// show the search data
}
});
} else if (string.length <= 1) {
// restore page content as of when it was loaded
}
});
Another thing I should ask, I should probably cache the results of the ajax, no?
setTimeout
in your code. – Tael