I am using Twitter bootstrap's typeahead via javascript to provide a typeahead for foursquare venues using this snippet of code :
function addLocationTypeaheadHandler() {
$('input#location').keyup(function() {callFoursquareForTypeahead()});
}
function callFoursquareForTypeahead() {
var inputQuery = $('input#location').val();
if (inputQuery.length == 3) {
$('input#location').typeahead({
source: function(query, process) {
var urlString = "https://api.foursquare.com/v2/venues/suggestcompletion?ll=" + $('#latitude-field').val() + "," + $('#longitude-field').val() +
"&radius=1000&client_id=" + clientid + "&client_secret=" + clientsec;
return $.get(urlString, {query: $('input#location').val()},
function(json) {
venueNames = [];
$.each(json.response.minivenues, function(index,value) {
venueNames.push(value.name);
});
return process(venueNames);
}
);
}
});
}
}
It currently works, but in my Network requests I can see each time I change the query, there is a new XHR request to foursquare. I have tried to minimize them using the (not so elegant) keyup event with the inputQuery length conditional but it is still being called.
I would like to know if there is there a way to minimize these requests
Late to the party, perhaps, but it looks like the new version of Typeahead will help you out here.
The new version has, built into its concept of Remote data sources, a rateLimitWait that allows you to cap the number of ms between each call that typeahead will attempt to make.
It also doesn't look like you need to bind it to keyup, since the examples say that it can listen to changes in the input field all by itself. That will help you avoid double-bindings that could wind up circumventing your rate limiting.