Question

I have some AJAX that shows a progress bar using setInterval() to get the scripts current progress. My problem is that I cannot seem to kill it when progress has reached 100%. I am not sure if this has something to with scope, but my handler is global, so I can't figure out why it's not working. Here's what I have:

function showLog(){
    document.getElementById('log').style.display = "block";
    clearInterval(inth);
    return false;
}

function startAjax(){
    var inth = setInterval(function(){
        if (window.XMLHttpRequest){ xmlhttpp=new XMLHttpRequest();}else{ xmlhttpp=new ActiveXObject("Microsoft.XMLHTTP"); }
        xmlhttpp.onreadystatechange=function(){
            if(xmlhttpp.readyState==4 && xmlhttpp.status==200){
                document.getElementById("sbar").innerHTML=xmlhttpp.responseText;
            }
        }
        xmlhttpp.open("POST","scrape.php",true);
        xmlhttpp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var sitelist = document.getElementById('website').value;
        var par = "website="+sitelist;
        xmlhttpp.send(par);
    }, 5000);
    return false;
}

Why is clearInterval not working? What am I doing wrong?

Was it helpful?

Solution

This is a scope issue, declare the var inth outside the function as a global variable. and use inth = setInterval(...) in the startAjax function.

As you said in your question, your handler is global. But the variable itself is not, so it can't be accessed outside the scope of the function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top