我每8秒使用ajax从服务器获取json数据。大部分时间都能正常工作,但即使条件为true,如果循环未执行,有时也会在2nd内执行代码。
setInterval(function () {
if (board.turn != board.mycolor) {
$.ajax({
type: 'post',
url: 'checkgamedata.php',
success: function (result) {
var obj = JSON.parse(result);
if (players[board.turn].lastturnno < obj.turnno) {
//Code inside this if loop is not executing
players[board.turn].lastturnno = obj.turnno;
for (var i = dataleft; i < obj.kodidata.length; i++) {
numbergot = grandom(obj.kodidata[i]);
process(numbergot);
if (obj.indexarr[i] != 'null') {
updatepawn(obj.indexarr[i]);
}
} //For loop end
if (board.turn != board.mycolor) {
dataleft = obj.kodidata.length;
} else {
dataleft = 0;
}
}
//If loop end
} //Success end
});
}
//Post end here
}, 8000);
//timeout end here
我执行ajax操作的结果是这样的{"kodidata":[["0.33","0.40","0.36","0.76"]],"indexarr":["2"],"turnno":"12"}
。
我通过使用alert在if循环之前检查了obj.turn和players [board.turn] .lastturnno的值,我可以看到obj.turn的值更大,但是如果循环未执行,代码仍然在其中。为什么?