2011-08-03 176 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這樣的調試器會讓它看起來更慢?)。我想你想要第一個匿名函數來設置第二個計時器。