2011-08-03 117 views
3

我正在尝试创建一个类似于http://projects.flowingdata.com/walmart/的增长图。jquery,每2秒添加一个元素

我使用https://github.com/marioestrada/jQuery-gMap做马平

什么我目前得到的是一个按钮,当我点击它,我要开始动画。 onclick代码是:

<script> 
    $("input.buttonB").click(function(){ 
     window.setTimeout(function() { 
      $('#map_canvas').gMap('addMarker', { 
       latitude: 41.60252, 
       longitude: -100.32855, 
       content: 'Some HTML content' 
       } 
      ); 
     }, 2000); 
     window.setTimeout(function() { 
      $('#map_canvas').gMap('addMarker', { 
       latitude: 11.60252, 
       longitude: -110.32855, 
       content: 'Some HTML content' 
       } 
      ); 
     }, 2000);   
    }); 
</script> 

问题是,标记不会在屏幕上每2秒出现一次。窗口等待4秒钟,然后同时显示它们两个。

有什么建议吗?

+0

在你的例子中,你不想第二次超出4000毫秒? –

+1

为什么你有两个超时? – Starx

+0

最终会有数百个元素每2秒显示一组。有两个超时,因为我误解了超时。 – Ted

回答

3

理想情况下,你应该有这样的事情(未经测试):

var markerData = [{ 
    lat: "something", 
    lng: "something", 
    html: "something"}, 
{ 
    lat: "something", 
    lng: "something", 
    html: "something" 
}]; 

function showNextMarker() { 
    var current = markerData.shift(); 
    $('#map_canvas').gMap('addMarker', { 
     latitude: current.lat, 
     longitude: current.lng, 
     content: current.html 
    }); 
} 

$("input.buttonB").click(function(){ 
    var i = window.setInterval(function() { 
     showNextMarker(); 
     if (markerData.length == 0) { 
      i = window.clearInterval(i); 
     }; 
    }, 2000);  
}); 
+0

太棒了!我看到shift()的值,在jQuery中并不知道它。 –

+1

@Michael Mao - 这是一个很老的JavaScript,它捕捉它实际上从数组中删除了第一个元素,但它可以是有用的,因为当你不需要重新使用数组时,因为解决方案使用'shift'的时间往往更短。 – karim79

+0

我喜欢这个解决方案。我测试了它,它工作。一个问题虽然 - 循环永远不会结束。 – Ted

0

JavaScript没有 “停止”,等待超时。因此,如果您将两个2秒超时设置为一个接一个,那么两秒钟后都会执行。

为什么你的代码应该执行秒后,我不能说。没有任何表示会。但是如果电脑繁忙,超时可能会延迟。超时只意味着尽快时间限制已经用完。

在任何情况下,我建议是这样的:

(function(){ 
    var markers = [ 
     { 
      latitude: 41.60252, 
      longitude: -100.32855, 
      content: 'Some HTML content' 
     }, 
     { 
      latitude: 11.60252, 
      longitude: -110.32855, 
      content: 'Some HTML content' 
     } 
     // add more here 
    ]; 

    function addMarker() { 
     $('#map_canvas').gMap('addMarker', markers.shift()); 

     if(markers.length > 0) { 
      setTimeout(addMarker, 2000); 
     } 
    } 

    $("input.buttonB").click(function(){ 
     addMarker(); 
    }); 
}()); 
0

样本HTML

<button>click</button> 
<div class="output"></div> 

的JS

$(function(){ 
    var coords = [ 
     {x:100, y:200}, 
     {x:5, y:10}, 
     {x:300, y:400} 
    ]; 

    var i = 0; 

    var displayCoord = function(){ 
     $("div").append('<p> x:' + coords[i].x + ' y:' + coords[i].y + '</p>'); 
     if(i < coords.length){ 
      i += 1; 
      setTimeout(displayCoord, 2000); 
     } 
    }; 

    $("button").click(displayCoord); 
}); 

See it on jsFiddle

0

它看起来像你会这两个事件都是在2s后发生的(不是4s--你是否使用了像FireBug这样的调试器会让它看起来更慢?)。我想你想要第一个匿名函数来设置第二个计时器。