在我的代码中的某个地方,我调用这个函数:
function call_bid_button(id)
{
bid_button(id);
var refreshIntervalId = setInterval(function(){bid_button(id)},1000);
}
如您所见,它调用函数 bid_button()
并为其设置一个间隔
。
我希望 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()
。显然,这是行不通的。那么正确的方法是什么?
谢谢
最佳答案
您实际上可以只传递对间隔的引用:
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
进行解析。
关于javascript - 如何让函数 `clearInterval`本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21733935/