所以现在我不断地发送xmlhttprequests,然后使用get to php脚本,该脚本使我回到了文件夹中的文件数量。
我使用setInterval()
重复了JavaScript函数,它的工作原理很好,但是我希望setInteral()
在我从PHP脚本中获得一定数量的一定数量。
这是我的代码:
<script>
function checkmedia(url,format) {
var format1 = format;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
progress = this.responseText;
document.getElementById("progress").innerHTML =
this.responseText;
}
};
xhttp.open("GET", 'checkfilecount.php?userurl='+url+'&act=run&format-option=' + format, true);
xhttp.send();
if(progress != "100") {
var media_progress = setInterval(checkmedia.bind(null,url,format1), 10000);
}
}
</script>
当我不断地调用此xmlhttprequest时,(对于表格),我正在收到内存泄漏。
欢迎任何类型的帮助。谢谢。
setInterval()
函数以指定的间隔重复调用函数。setTimeout()
函数在指定延迟后调用一次函数。您使用了错误的...
您正在获取内存泄漏,因为您正在从内部调用 setInterval()
,因此每次运行它都会产生额外的间隔,然后这些间隔,然后这些间隔等等,而无处您清除间隔吗?
您可以从功能外部调用setInterval()
,然后修改您的if
以决定是否致电clearInterval()
停止整个过程(Blaze Sahlzen的答案显示如何整洁地做到这一点),但我认为仅使用setTimeout()
是更简单的而是:
function checkmedia(url, format) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
progress = this.responseText;
document.getElementById("progress").innerHTML = this.responseText;
if (progress != "100") {
setTimeout(checkmedia.bind(null, url, format), 10000);
}
}
};
xhttp.open("GET", 'checkfilecount.php?userurl=' + url + '&act=run&format-option=' + format, true);
xhttp.send();
}
您想添加一些代码来处理Ajax错误,但是我将其作为读者的练习。
这是您可以处理这种情况的一种方法:
function check(url, format) {
function checkmedia(url, format) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("progress").innerHTML = this.responseText;
if (Number(this.responseText) === 100) {
clearInterval(media_progress);
}
}
};
xhttp.open("GET", 'checkfilecount.php?userurl=' + url + '&act=run&format-option=' + format, true);
xhttp.send();
}
var media_progress = setInterval(checkmedia.bind(null, url, format), 10000);
}
check('your_url', 'your_format');
使用clearInterval
,您可以在达到特定条件时停止setInterval
功能。