简体   繁体   English

clearInterval无法与XMLHttpRequest一起使用

[英]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. 我使用XMLHttpRequest,它的setInterval延迟为5s来获取数据。 If the status of the request is 200. The code works well. 如果请求的状态为200。该代码运行良好。 However, if the status is not 200. The clearInterval will not work but console.log still works. 但是,如果状态不是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);

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. 问题在于,有可能调用clearInterval并且XHR正在等待响应。 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. 如果您希望定期XHR在启动另一个XHR之前等待其响应,则递归setTimeout是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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