我正在尝试在数据库中获取下次游戏的结果。我使用带有 5 秒延迟的 setInterval 的 XMLHttpRequest 来获取数据。如果请求的状态是 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
是更好的选择。
关于javascript - clearInterval 不适用于 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43828706/