javascript - 如何让函数 `clearInterval`本身?

标签 javascript ajax setinterval clearinterval

在我的代码中的某个地方,我调用这个函数:

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/

相关文章:

javascript - 解构对象数组,默认值

javascript - 三个js销毁渲染器

javascript - 我可以只使用一个请求来填充同一个 html 元素吗?

javascript - 使用大量术语,搜索页面文本并用链接替换单词

javascript - 常量 setInterval 如何影响页面功能(是否会减慢响应时间或损害用户命令等)?

javascript - 多次调用 jQuery 插件时 SetInterval 发生冲突

javascript - 设置间隔(JavaScript): are there known bugs?

javascript - Angular : Select combination from a list

javascript - 对象的不透明度 slider

Java Wicket - 在 AJAX 之前调用 javascript ( JQuery )