Somewhere in my code, i call this function:

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

Which as you can see calls the function bid_button() and sets an interval for it.

I want bid_button() to activate clearInterval() for itself. Here's 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;
}

As you can see, i'm trying to call clearInterval() from another function. Obviously, this won't work. What's the correct way to do it though?

Thanks

有帮助吗?

解决方案

You can actually just pass a reference to the interval:

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

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

This works because the callback function in the interval is called later.

Keep in mind though that because of the way bid_button is implemented some intervals may not get cleared. If you lose your internet connection for instance, it will keep trying and trying. The requests will resolve with status=0.

其他提示

Set refreshIntervalId as a global variable, or at least within the scope of both functions.

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;
}
var timer = setInterval(function(){
   alert('delayed 1ms');
},1000);

When this is through, as long as you arent calling it again, it is through. If you are,

clearInterval(timer);

IF the timer is wrapped in another function, the var makes it scoped to that function. You can either remove it to make it a global variable or execute it later in the same scope of the wrapped function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top