better handling of xhr requests
This commit is contained in:
parent
7b516bf68c
commit
16459b7c16
47
trivabble.js
47
trivabble.js
|
@ -455,6 +455,8 @@
|
|||
}
|
||||
|
||||
var pollingServer = false;
|
||||
var pollingReady = false;
|
||||
var retriedImmediately = false;
|
||||
|
||||
function fatalError(e) {
|
||||
console.error(e);
|
||||
|
@ -661,15 +663,21 @@
|
|||
}
|
||||
|
||||
function send(data) {
|
||||
var xhr = new XMLHttpRequest();
|
||||
if (!pollingReady && ((data.cmds && data.cmds.length) && data.cmds[0].cmd !== "joinGame")) {
|
||||
send([]);
|
||||
setTimeout(send.bind(null, data), POLLING_DELAY);
|
||||
return;
|
||||
}
|
||||
|
||||
xhr.open("POST", "/:trivabble", true);
|
||||
xhr.setRequestHeader("Content-Type", "text/plain");
|
||||
xhr.send(JSON.stringify(data));
|
||||
|
||||
var thisRequestIsPolling = false, currentIndex = 0, expectedLength = 0;
|
||||
var thisRequestIsPolling = false;
|
||||
var currentIndex = 0;
|
||||
var expectedLength = 0;
|
||||
|
||||
if (!data.cmds || !data.cmds.length) {
|
||||
if (pollingServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
pollingServer = true;
|
||||
thisRequestIsPolling = true;
|
||||
}
|
||||
|
@ -678,10 +686,19 @@
|
|||
blockMove++;
|
||||
}
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
|
||||
xhr.open("POST", "/:trivabble", true);
|
||||
xhr.setRequestHeader("Content-Type", "text/plain");
|
||||
xhr.send(JSON.stringify(data));
|
||||
|
||||
xhr.onreadystatechange = function () {
|
||||
// TODO error handling
|
||||
|
||||
if (xhr.readyState === 3 && thisRequestIsPolling) {
|
||||
if (xhr.readyState === 2 && thisRequestIsPolling) {
|
||||
pollingReady = true;
|
||||
} else if (xhr.readyState === 3 && thisRequestIsPolling) {
|
||||
pollingReady = true;
|
||||
while (true) {
|
||||
if (!expectedLength) {
|
||||
var i = currentIndex;
|
||||
|
@ -717,6 +734,8 @@
|
|||
fatalError(e);
|
||||
}
|
||||
|
||||
retriedImmediately = false;
|
||||
|
||||
if (msgs instanceof Array) {
|
||||
for (var i = 0; i < msgs.length; i++) {
|
||||
handleReceivedData(msgs[i]);
|
||||
|
@ -731,7 +750,19 @@
|
|||
} else if (xhr.readyState === 4) {
|
||||
if (thisRequestIsPolling) {
|
||||
pollingServer = false;
|
||||
setTimeout(sendCmds.bind(null, []), POLLING_DELAY);
|
||||
pollingReady = false;
|
||||
|
||||
if (retriedImmediately) {
|
||||
setTimeout(sendCmds.bind(null, []), POLLING_DELAY);
|
||||
} else {
|
||||
retriedImmediately = true;
|
||||
sendCmds([])
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (xhr.status === 0 || xhr.status >= 300) {
|
||||
setTimeout(send.bind(null, data), POLLING_DELAY);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue