简体   繁体   中英

clearInterval not working with XMLHttpRequest

I'm trying to get the result, next time of the game in database. I used XMLHttpRequest with 5s delay of setInterval to fetch data. If the status of the request is 200. The code works well. However, if the status is not 200. The clearInterval will not work but console.log still works.

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);

UPDATE: recursive function

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();
}

Am I doing it the right way or should I change it to recursive function? Thanks.

-- Lara

The problem is that there's a possibility where the clearInterval is called and an XHR is pending a response. When the browser receives the response, the timer is long gone, but still has to handle the response.

If you want your periodic XHR to wait for the response of the previous before launching another, the recursive setTimeout is a better option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM