please give me some clue for this javascript problem.
I have a global variable markers. And try to push every marker to markers.
But the problem is , after push to markers. i was trying to alert the value inside function and outside function. the result is totally different. markers inside function give me array of marker, but markers outside stay empty. Why i got different value of markers global variable?
This is the snippet of my code:
for (var i = 0; i < netotal; i++) {
setTimeout(function () {
marker = new google.maps.Marker({
position: pos[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
icon: neicon
});
iterator++;
markers.push(marker);console.log(markers);
}, i * 50);
}
alert (markers);
Thank you for your kind help or clue.
You’re pushing to
markersin a function that’s called usingsetTimeout, so the push won’t happen until some time later. But you’re callingalert(markers)immediately, before any of the timeouts have occurred. So the array is empty at that time.UPDATE:
To see the final contents of
markers, you need anothersetTimeout: