gpt4 book ai didi

javascript - 如何使用 AJAX 和 PHP 持续检查一个文件夹中有多少文件

转载 作者:行者123 更新时间:2023-11-30 09:38:34 26 4
gpt4 key购买 nike

所以现在我不断将带有 GET 的 xmlhttprequests 发送到 PHP 脚本,该脚本返回文件夹中的文件数量。

我用 setInterval() 重复了 javascript 函数,它工作得很好,但我希望 setInteral() 在我返回某个特定值时立即停止来 self 的 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() 函数在指定延迟后一次 调用一个函数。你用错了……

你正在发生内存泄漏,因为你正在从 inside 函数调用 setInterval(),所以每次它运行时都会产生一个额外的间隔,然后那些生成它们自己的等等,而您没有清除间隔。

您可以从函数外部调用 setInterval(),然后修改您的 if 来决定是否调用 clearInterval() 来停止整个事情(Blaze Sahlzen's answer 展示了如何巧妙地做到这一点),但我认为只使用 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 错误,但我会将其留作读者练习。

关于javascript - 如何使用 AJAX 和 PHP 持续检查一个文件夹中有多少文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42290029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com