我試圖在數據庫中獲得下一次遊戲結果。我用XMLHttpRequest以5s延遲setInterval來獲取數據。如果請求的狀態是200.代碼運行良好。但是,如果狀態不是200. clearInterval將不起作用,但console.log仍然有效。clearInterval不能與XMLHttpRequest一起使用
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:遞歸函數
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 –