2013-03-29 158 views
0

我有被插入到另一個HTML文件中使用AJAX(通過點擊按鈕)一個div的HTML文件product.html。有一個在product.html定時器如下:多個副本:如何確保只有一個副本運行

product.html

<!-- HTML stuff --> 
... 

Bid time of the product: <div id="displayTime"></div> 

... 
<!-- HTML stuff --> 


<div id="testChange"> 
<script> 
$(document).ready(function() { 

    function updateTime() { 
    var newContent = $("#testChange").html(); 
    if (newContent != oldContent) { // If the content of "testChange" changes, stop the timer 
     return; 
    } 
    timeStr = ... // prepare the time for display 
    $("#displayTime").html(timeStr); 
    setTimeout(updateTime, 1000); 
    } 

    function startUpdatingTime() { 
    oldContent = $("#testChange").html(); 
    updateTime(); 
    } 

startUpdatingTime(); 

</script> 
</div> 

當我點擊,使得文件product.html被插入通過AJAX到另一個HTML的DIV的按鈕。定時器運行正常。但是,當我再次單擊該按鈕時,顯然有兩個計時器正在運行。如果再次點擊,則會有多個計時器正在運行。 displayTime div閃爍,因爲很多定時器試圖更新它。我的問題:我如何檢查是否已有計時器正在運行,以便不需要運行新計時器。或者我該如何阻止舊的?

回答

1

只要使用clearTimeout如下貼:

$(document).ready(function() { 

    var timeout, oldContent; 

    function updateTime() { 
    var newContent = $("#testChange").html(); 
    if (newContent != oldContent) { // If the content of "testChange" changes, stop the timer 
     return; 
    } 
    timeStr = ... // prepare the time for display 
    $("#displayTime").html(timeStr); 

    if (timeout){ 
     window.clearTimeout(timeout); 
    } 
    timeout = window.setTimeout(updateTime, 1000); 
    } 

    function startUpdatingTime() { 
    oldContent = $("#testChange").html(); 
    updateTime(); 
    } 

startUpdatingTime(); 

}); 
+0

明白了,非常感謝。 –

相關問題