polling.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /** @const @type {number} */
  2. var POLL_INTERVAL = 5000;
  3. function initPolling() {
  4. lazyGetPseudonyme(function(pseudo) {
  5. if (pseudo) {
  6. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  7. if (resp) {
  8. GRID = new Grid(resp, pseudo);
  9. if (resp["players"]) {
  10. GRID.updatePlayers(resp["players"]);
  11. if (!GRID.playerSelf)
  12. GRID.playerSelf = GRID.players[GRID.playerSelfId];
  13. onPlayersUpdated();
  14. }
  15. if (resp["grid"]) {
  16. GRID.update(resp["grid"]);
  17. uiCreateGrid();
  18. }
  19. if (resp["gridTime"]) {
  20. GRID.gridTime = parseInt(resp["gridTime"], 10);
  21. } else {
  22. scheduleNextPoll();
  23. }
  24. KNOWN_VERSION = Math.max(KNOWN_VERSION, resp["v"] || 0);
  25. } // TODO else cannot init party
  26. });
  27. } // TODO else cannot init pseudo
  28. });
  29. }
  30. function pollNow() {
  31. if (pollNow.polling !== true) {
  32. if (pollNow.pollSchedule) {
  33. clearTimeout(pollNow.pollSchedule);
  34. pollNow.pollSchedule = 0;
  35. }
  36. pollNow.polling = true;
  37. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  38. if (pollNow.stopped !== true) {
  39. //TODO manage network error
  40. pollNow.polling = false;
  41. if (resp) {
  42. updateOnPollResult(resp);
  43. }
  44. scheduleNextPoll();
  45. }
  46. });
  47. }
  48. }
  49. function stopPolling() {
  50. pollNow.stopped = true;
  51. if (pollNow.pollSchedule) {
  52. clearTimeout(pollNow.pollSchedule);
  53. pollNow.pollSchedule = 0;
  54. }
  55. }
  56. function scheduleNextPoll() {
  57. pollNow.stopped = false;
  58. if (!pollNow.pollSchedule)
  59. pollNow.pollSchedule = setInterval(pollNow, POLL_INTERVAL);
  60. };