Reputation: 458
On my page I'm using MaxMind to populate a users long/lat.
I'm also using a script (containing the haversine formula) to take the users long/lat and assign a distance parameter to an object that relates to a store location.
Once the distance has been stored I want to run the following loop
for(i=0; i<cities.length; i++){
var newLat = cities[i].lat;
var newLon = cities[i].lon;
getDistanceFromLatLonInKm(userLat,userLon,newLat,newLon);
var lowest = 1000
if(cities[i].distance< lowest){lowest = cities[i].distance}
}
cities.sort(function(a, b) {
return a.distance - b.distance;
})[0]
var div = document.getElementById('test');
if(cities[0].fax == null){
div.innerHTML = div.innerHTML + cities[0].street + '<br />' + cities[0].city + '<br />' + cities[0].postal + '<br /><b>Phone:</b>' + cities[0].phone;
}else{div.innerHTML = div.innerHTML + cities[0].street + '<br />' + cities[0].city + '<br />' + cities[0].postal + '<br /><b>Phone:</b>' + cities[0].phone + '<br /><b>Fax:</b>' + cities[0].fax;
}
The only thing is that since there's a delay on the coordinates showing up, the loop can't run right away. How can I run this loop after the coordinates are populated?
Upvotes: 0
Views: 41
Reputation: 63732
You can use the setTimeout
function, eg.:
setTimeout(function () { yourCode... }, 5000);
However, that is rarely the proper solution. Instead, you should look in the API of your data source, it probably has a callback function you can use to get notified of the data being available. That's the proper way to wait for data. If there's no such way, you'll have to use setTimeout
(in fact, call it again if data isn't available yet when you get inside the delayed code).
Upvotes: 1