Reputation: 107
I'm trying to make my overlays appear more slowly instead of all at the same time. The code works perfectly until I add setTimeout. When I try to run it, console says that latLng is not defined.
After searching, I see a lot of people have had similar problems but none of them seem to answer my question.
Here's the function. Let me know if you need more of the code.
function getAndDrop() {
$.ajax({
url : 'php/locationarray.php',
success : function(data) {
latLng = data.split(" ");
for ( i = 0; i < latLng.length; i++) {
setTimeout(function(){
var loc = latLng[i].split("|");
if (marker.length > maxOverlays)
clearSingleOverlay();
addMarker(loc[0], loc[1]);
}, i*200);
}
}
});
}
Edit: latLng is defined as a global above. It was local. I made it global in an attempt to debug
Upvotes: 0
Views: 81
Reputation: 19588
You need a closure:
success : function(data) {
var latLng = data.split(" ");
for ( i = 0; i < latLng.length; i++) {
(function(LL){
setTimeout(function(){
var loc = LL.split("|");
if (marker.length > maxOverlays)
clearSingleOverlay();
addMarker(loc[0], loc[1]);
}, i*200);
})(latLng[i]);
}
}
read here for clarification: Please explain the use of JavaScript closures in loops
ps. you should create a dedicated function to handle processing in the loop:
ie: for (...) handleCurrent();
Upvotes: 4
Reputation: 16636
That is because latLng
is not available in the closure. Could you try adding var
before the latLng
declaration:
success : function(data) {
var latLng = data.split(" ");
for ( i = 0; i < latLng.length; i++) {
setTimeout(function(){
var loc = latLng[i].split("|");
if (marker.length > maxOverlays)
clearSingleOverlay();
addMarker(loc[0], loc[1]);
}, i*200);
}
}
Upvotes: -1