2017-02-17 30 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

相關問題