2017-02-17 84 views
1

所以现在我不断地用GET发送xmlhttprequests到一个PHP脚本,这个脚本让我回到文件夹中的文件数量。如何连续检查AJAX和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> 

由于我continiously调用这个XMLHttpRequest的和多次(一个表)我得到了内存泄漏。

欢迎任何形式的帮助。谢谢。

回答

2

setInterval()函数以指定的间隔重复调用一个函数。 setTimeout()函数在指定的延迟后调用一次函数。你用错了一个...

你得到一个内存泄漏,因为你是从呼吁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错误,但我会留给读者作为练习。

+0

我认为这是一个更好的方法,因为'setInterval'不会等待前一个实例完成处理,如果它需要很长时间,我们可能会有多个实例在运行,导致内存再次泄漏。这是一个可能的情况? –

+1

@BlazeSahlzen - 很明显,'setTimeout()'版本一次最多保证一个ajax调用,所以我认为这样更安全,虽然我只是意识到我简化了一点,因为我应该这样做,因为我应该把在'onreadstatechange'处理程序中(如果我现在要这样做),并且我应该允许发生ajax错误(我不会为此烦恼)。即使发生错误,至少'setInterval()'也会继续轮询。 – nnnnnn

+0

我在这个答案中使用的代码,它完美的作品!谢谢。尽管如此,两个答案都非常有帮助,我从他们身上学到了很多东西。谢谢 – userlip

2

下面是你可以接近这种情况的一种方法:

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功能,当你达到一个特定的条件。

+1

不错的工作。你让我不必在自己的答案中写下这个技巧,而只是把它和你的联系起来。 – nnnnnn

+0

谢谢!但你仍然打败了我的答案,但:p @ nnnnnn –

+0

哦,好吧。如果我花时间在前面写出这两个变体,你可能是第一个,但我认为'setTimeout()'版本更容易,所以这就是我所做的。 – nnnnnn

相关问题