2013-03-28 49 views
0

我正在使用谷歌地圖,並希望顯示多個標記。 如果您輸入城市的名稱,地圖會跳轉到該地區,您將獲得該地區所有公司的列表。按下按鈕,每個公司都會顯示在地圖上。 該標誌應延遲小滴所以我做了這樣的功能:jQuery break .each()超時

$('#show_markers').click(function() 
{ 
    $('.div_with_information').each(function(index) 
    { 
    var location = $(this);//includes multiple infomations like lat, lng, name, info... 
    setTimeout(function() 
    { 
     set_marker(location);//function to create google marker with infobox ect. 
    },100*index); 
    }); 
}); 

這工作得很好。我需要拖延動畫,並檢查標記的座標。 但有時候有很多標記需要花費很多時間才能刪除腳本。

我在找的是一個完全停止「標記雨」的功能。

$('#stop_button').click(stop_drop); 

我嘗試了很多東西,但沒有任何工作,因爲我希望。 我希望你有一些好的想法。

+0

你想明確地停止它還是隻停留一段時間?如果明確,setTimeout返回一個整數,該整數可用於使用函數clearTimeout取消回調。因此,將這些整數存儲在某個地方,並在您想要停止下雨時調用clearTimeout。 – Loamhoof

+0

此刻一站就夠了 –

回答

0
var is_running = false; 
var timeout; 

$('#show_markers').click(function() 
{ 
    if (is_running) 
    return; 

    is_running = true; 

    var index = 0; 
    var divs = $('.div_with_information'); 
    var num = divs.length; 

    timeout = setTimeout(on_set_marker_event, 100); 

    function on_set_marker_event() 
    { 
    var location = divs.eq(index); 
    set_marker(location); 

    index++; 

    if (is_running && index < num) 
     timeout = setTimeout(on_set_marker_event, 100); 
    }); 
}); 

$('#stop_button').click(function() 
{  
    is_running = false; 
    clearTimeout(timeout); 
}); 
+0

就是這樣!謝謝。我知道我必須調用clearTimeout(),但我不知道如何將它與.each() –