【问题标题】:Avoid setTimeout in ajax callback function在ajax回调函数中避免setTimeout
【发布时间】:2011-05-17 21:45:45
【问题描述】:

有没有其他方法可以防止setTimeout 成为必要?

function initialize(){

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

      //do some stuff with xml like...
      var icons = xml.documentElement.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?
   });

}

【问题讨论】:

  • 它给出了什么错误? marker 是从哪里来的?
  • 它为谷歌地图的markerManager实用程序提供了一个api错误

标签: javascript jquery ajax google-maps google-maps-markers


【解决方案1】:

很难判断哪里出了问题,因为您没有提供您得到的错误或创建标记的代码。尝试猜测,最有可能发生的事情是您运行以创建标记并可能初始化地图的代码不是同步运行,而是异步运行。如果涉及一些 ajax 调用,这肯定是这种情况,这意味着地图/管理器系统在调用最后一个 javascript 行时还没有准备好,但是在一段时间之后并且肯定在函数退出之后.

为了避免 setTimeout 会引入不必要的延迟并且很容易中断,如果在某些情况下需要更多时间,您需要查看创建标记的代码并查看是否存在定义的回调/事件,标志着初始化过程的完成。

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2019-07-25
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多