Reputation: 111
I am implementing a autocomplete with Javascript and Google Maps geocode method (using keyup event on input) and some times I receive the previous search before the actual one.
My intention is to cancel previous call if it hasn't finished. Can anybody can help me?
getAddressLatLng : function(text,callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : text,
region : Utils.getRegion()
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results);
}
});
},
Upvotes: 4
Views: 950
Reputation: 1671
You could make a global request counter, and only perform your callback behavior if it does not increase. e.g.
var requests = 0;
...
getAddressLatLng : function(text,callback) {
var requestNum;
requests++;
requestNum = requests;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : text,
region : Utils.getRegion()
},
function(results, status) {
if(requestNum != requests) return;
if (status == google.maps.GeocoderStatus.OK) {
callback(results);
}
});
},
I would also suggest debouncing/throttling your function so you don't waste bandwidth generating unnecessary requests (underscore has convenient functions for doing this).
Upvotes: 2