[英]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.