2014-02-12 25 views
0

某處在我的代碼,我調用這個函數:如何讓一個函數`clearInterval`本身?

function call_bid_button(id) 
{ 
    bid_button(id); 
    var refreshIntervalId = setInterval(function(){bid_button(id)},1000); 
} 

正如你可以看到通話功能bid_button()並設置interval它。

我想bid_button()自己激活clearInterval()。下面是bid_button()

function bid_button(id) 
{ 
    if (window.XMLHttpRequest) 
    { 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText=='') 
    { 
     document.getElementById("bid_button").innerHTML=xmlhttp.responseText; 
     clearInterval(refreshIntervalId); 
    } 

    } 
    xmlhttp.open("GET","the_bid_button.php?id="+id,true); 
    xmlhttp.send(); 
    return false; 
} 

正如你所看到的,我試圖調用clearInterval()從另一個功能。顯然,這是行不通的。儘管如此,正確的方法是什麼?

由於

回答

3

實際上,你可以只通過該區間參考:

var interval_id; 
interval_id = setInterval(function(){bid_button(id, interval_id); },1000); 

function bid_button (id, interval_id) { 
    clearInterval(interval_id); 
} 

這工作,因爲在區間的回調函數稍後被調用。

請記住,由於實施bid_button的方式,某些間隔可能無法清除。例如,如果你失去了互聯網連接,它將繼續嘗試和嘗試。請求將通過status=0解決。

+0

我想過,但我認爲這是行不通的。現在我明白了它爲什麼起作用。謝謝 –

2

refreshIntervalId作爲全局變量,或至少兩種功能的範圍內。

var refreshIntervalId; 

function call_bid_button(id) 
{ 
    bid_button(id); 
    refreshIntervalId = setInterval(function(){bid_button(id)},1000); 
} 

function bid_button(id) 
{ 
    if (window.XMLHttpRequest) 
    { 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText=='') 
    { 
     document.getElementById("bid_button").innerHTML=xmlhttp.responseText; 
     clearInterval(refreshIntervalId); 
    } 

    } 
    xmlhttp.open("GET","the_bid_button.php?id="+id,true); 
    xmlhttp.send(); 
    return false; 
} 
+0

我知道這可行,但我認爲這是不好的編程... –

+0

如果你每次調用不止一次調用'bid_button',它們中的一些不會被清除。我不會推薦這個解決方案。 _「使用全局變量」_應該引發一些警鐘。 – Halcyon

0
var timer = setInterval(function(){ 
    alert('delayed 1ms'); 
},1000); 

當這是通的,只要你的arent再次調用它,它是通過。 如果你是

clearInterval(timer); 

如果定時器被包裹在另一個功能,var使其作用範圍包括該功能。您可以將其刪除以使其成爲全局變量,也可以稍後在包裝函數的相同範圍內執行它。

相關問題