簡體   English   中英

clearInterval無法與XMLHttpRequest一起使用

[英]clearInterval not working with XMLHttpRequest

我試圖在下次數據庫中獲得結果。 我使用XMLHttpRequest,它的setInterval延遲為5s來獲取數據。 如果請求的狀態為200。該代碼運行良好。 但是,如果狀態不是200。clearInterval將不起作用,但console.log仍將起作用。

var _resInterval;
_resInterval = setInterval(function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if (xhr.status === 200) {
      var _resp = JSON.parse(xhr.responseText);
      console.log(_resp);

      if (parseInt(_resp.interval) >= 0) {
        clearInterval(_resInterval);
        restartGame(parseInt(_resp.interval));
      }
    } else {
      console.log("error");
      clearInterval(_resInterval);
    }
  };
  xhr.send();
}, 5000);

更新:遞歸函數

function getGameResult() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if (xhr.status === 200) {
      var _resp = JSON.parse(xhr.responseText);
      console.log(_resp);

      if (parseInt(_resp.interval) >= 0 && _resp.result != "Not available") {
        restartGame(parseInt(_resp.interval));
      } else {
        setTimeout(function() {
          getGameResult();
        }, 5000);
      }
    }
  };
  xhr.send();
}

我是以正確的方式執行操作還是應該將其更改為遞歸函數? 謝謝。

-拉拉

問題在於,有可能調用clearInterval並且XHR正在等待響應。 當瀏覽器收到響應時,計時器早已消失,但仍必須處理響應。

如果您希望定期XHR在啟動另一個XHR之前等待其響應,則遞歸setTimeout是更好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM