2015-10-17 50 views
-1

我需要在一段時間間隔後連續調用一個函數,所以我遵循此link上提供的解決方案。當再次調用JS函數時,JS函數在較短的時間內開始執行

這裏是JS代碼。

function displayLiveLocation() 
    { 
     var location = new Array(); 
     var currentcord = new Array(); 
     $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() { 
      location.push($(this).val()); 
      var current = $(this).val(); 
      currentcord.push($('#'+current+'_H').val()); 
     }); 
     copyofAutotrack(currentcord , location); 
     setTimeout(function() { 
      display(); 
     }, 15000); 

    } 

這裏是HTML代碼。

<div class="checkbox"> 
    <input type="checkbox" onclick="displayLiveLocation()" value="0358911020092058" name="IMEISeries[]" class="IMEISeriesClass[]">  
    <input type="hidden" value="26.79997253418,75.799194335938" id="0358911020092058_H"> 
    </div> 

有多個複選框和隱藏字段與上面類似的唯一id。當點擊一個複選框時,相應的功能以15秒的間隔開始執行。然而,當另一個複選框被點擊時,同樣的事情發生,使得該函數以較小的時間間隔執行,因爲另一個函數調用被執行。我只想在15秒內執行此功能。任何幫助,將不勝感激。提前致謝。

我不知道如何搜索這個網站,所以我問了這個問題。

+1

學習如何使用'clearTimeout()' – charlietfl

回答

2

當你點擊複選框另一個第一時間超時執行前,從第一次點擊的超時會第一次點擊後15秒發生,但第二次點擊發生數據。

如果你希望他們用自己的數據集單獨發生,則可以將數據發送到時你怎麼稱呼它,而不是使用當前數據有它的功能:

function displayLiveLocation() 
{ 
    var location = new Array(); 
    var currentcord = new Array(); 
    $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() { 
     location.push($(this).val()); 
     var current = $(this).val(); 
     currentcord.push($('#'+current+'_H').val()); 
    }); 
    copyofAutotrack(currentcord, location); 
    setTimeout(function() { 
     display(currentcord, location); 
    }, 15000); 

} 

如果你不是想完全停止第一超時,只是等待秒超時,你可以使用clearTimeout

var displayTimeout = null; 

function displayLiveLocation() 
{ 
    var location = new Array(); 
    var currentcord = new Array(); 
    $('input[type=checkbox][name="IMSeries[]"]:checked').each(function() { 
     location.push($(this).val()); 
     var current = $(this).val(); 
     currentcord.push($('#'+current+'_H').val()); 
    }); 
    copyofAutotrack(); 
    if (displayTimeout != null) { 
     clearTimeout(displayTimeout); 
    } 
    displayTimeout = setTimeout(function() { 
     displayTimeout = null; 
     display(currentcord, location); 
    }, 15000); 

} 
+0

感謝您的解決方案。 –

1

每次單擊複選框時,都會啓動一個新的超時。如果用戶在幾秒鐘內點擊3個複選框,則會調用3個超時,並立即運行。

一種解決方案,以阻止最後超時你調用一個新的使用clearTimeout前:

var timeoutActive = false; // status of the timeout 

function displayLiveLocation() 
{ 
    // your code 

    window.clearTimeout(timeoutActive); // cancels the last timeout 
    timeoutActive = window.setTimeout(function() { // sets the new timeout and saves the status in the global variable timeoutActive 
     display(); 
    }, 15000); 

} 
+0

謝謝你的解決方案:) –