【发布时间】:2017-05-07 15:44:08
【问题描述】:
我正在尝试在数据库中获得下一次游戏的结果。我使用 XMLHttpRequest 和 5s 延迟 setInterval 来获取数据。如果请求的状态是 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 不起作用”是什么意思?
-
@EvanTrimboli 嗨,感谢您抽出时间回答我的问题。 clearInterval 将停止 setInterval,对吗?它不会停止运行代码。我不确定使用递归函数是否适合这种情况,但递归对我来说效果很好。等待一些javascript大侠分享知识:D
标签: javascript