polling.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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);
  28. updateOnPollResult(resp);
  29. GRID.playerSelf = GRID.players[pseudo];
  30. scheduleNextPoll();
  31. } // TODO else cannot init party
  32. });
  33. } // TODO else cannot init pseudo
  34. });
  35. }
  36. function pollNow() {
  37. if (pollNow.polling !== true) {
  38. if (pollNow.pollSchedule) {
  39. clearTimeout(pollNow.pollSchedule);
  40. pollNow.pollSchedule = 0;
  41. }
  42. pollNow.polling = true;
  43. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  44. pollNow.polling = false;
  45. if (resp) {
  46. updateOnPollResult(resp);
  47. }
  48. scheduleNextPoll();
  49. });
  50. }
  51. }
  52. function scheduleNextPoll() {
  53. if (!pollNow.pollSchedule)
  54. pollNow.pollSchedule = setInterval(pollNow, POLL_INTERVAL);
  55. };