[英]Javascript - Clearing the interval and setinterval scope
I have some AJAX that shows a progress bar using setInterval()
to get the scripts current progress. 我有一些AJAX,它使用
setInterval()
显示进度条以获取脚本当前进度。 My problem is that I cannot seem to kill it when progress has reached 100%. 我的问题是,当进度达到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? 为什么clearInterval不起作用? What am I doing wrong?
我究竟做错了什么?
This is a scope issue, declare the var inth
outside the function as a global variable. 这是一个范围问题,将函数外部的
var inth
声明为全局变量。 and use inth = setInterval(...)
in the startAjax
function. 并在
startAjax
函数中使用inth = setInterval(...)
。
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.
但是变量本身不是,所以它不能在函数范围之外访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.