开发者

Avoid setTimeout in ajax callback function

Is there any other way to do this that might prevent the setTimeout to be necessary?

function initialize(){

   $.get('test.xml', function(xml){

      //do some stuff with xml like...
      var icons = xml.docume开发者_如何学编程ntElement.getElementsByTagName("icon");
        for(var i = 0; i < icons.length; i++) {
           var iconImage = icons[i].getAttribute("image"),
        }

      //do more things to create markers like...
      markers.push(marker);

      //try to add markers to map
      //this will give an error
      addMarkers(markers);

      //setTimeout makes it work
      setTimeout("addMarkers(markers)", 300);

      //is there any way to avoid the timeout?
   });

}


It is hard to tell what is wrong, since you aren't providing the error you get or the code that creates the marker. Trying to guess, the most probably thing happening is that the code you run to create the markers and perhaps to initialize the map doesn't run synchronously, but asynchronously. This will be definitely the case if there are some ajax calls involved and it means that the map/manager system aren't ready by the time the last javascript line is called, but after some period of time and by sure after the function has exited.

In order to avoid the setTimeout, which among others will introduce an unnecessary delay and is very easy to break, should more time is needed in certain conditions, you need to look at the code that creates the markers and see if there is a callback/event defined, which marks the completion of the initialization procedure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜