polling.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /** @const @type {number} */
  2. var POLL_INTERVAL = 5000;
  3. function doGet(url, callback) {
  4. var xhr = new XMLHttpRequest();
  5. xhr.onreadystatechange = function(e) {
  6. if (xhr.readyState === 4) {
  7. var resp = null;
  8. if (xhr.status === 200) {
  9. resp = xhr.response;
  10. try {
  11. resp = JSON.parse(/** @type {string} */ (resp));
  12. } catch (e) {
  13. resp = null;
  14. }
  15. }
  16. callback(xhr.status, resp);
  17. }
  18. };
  19. xhr.open('GET', url, true);
  20. xhr.send(null);
  21. }
  22. function initPolling() {
  23. lazyGetPseudonyme(function(pseudo) {
  24. if (pseudo) {
  25. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  26. if (resp) {
  27. GRID = new Grid(resp, pseudo);
  28. if (resp["players"]) {
  29. GRID.updatePlayers(resp["players"]);
  30. if (!GRID.playerSelf)
  31. GRID.playerSelf = GRID.players[GRID.playerSelfId];
  32. onPlayersUpdated();
  33. }
  34. if (resp["grid"]) {
  35. GRID.update(resp["grid"]);
  36. uiCreateGrid();
  37. }
  38. KNOWN_VERSION = Math.max(KNOWN_VERSION, resp["v"] || 0);
  39. scheduleNextPoll();
  40. } // TODO else cannot init party
  41. });
  42. } // TODO else cannot init pseudo
  43. });
  44. }
  45. function pollNow() {
  46. if (pollNow.polling !== true) {
  47. if (pollNow.pollSchedule) {
  48. clearTimeout(pollNow.pollSchedule);
  49. pollNow.pollSchedule = 0;
  50. }
  51. pollNow.polling = true;
  52. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  53. pollNow.polling = false;
  54. if (resp) {
  55. updateOnPollResult(resp);
  56. }
  57. scheduleNextPoll();
  58. });
  59. }
  60. }
  61. function scheduleNextPoll() {
  62. if (!pollNow.pollSchedule)
  63. pollNow.pollSchedule = setInterval(pollNow, POLL_INTERVAL);
  64. };