1
0

workflow.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var
  2. /**
  3. * @type {number} next period to wait before next retry in case of failure, in seconds
  4. **/
  5. NEXT_RETRY = 5
  6. ;
  7. function poll(callback) {
  8. var xhr = new XMLHttpRequest();
  9. xhr.timeout = 18000; // 2 min timeout
  10. xhr.timeout = 1800;
  11. xhr.onreadystatechange = function(e) {
  12. if (xhr.readyState === 4) {
  13. if (xhr.status === 0) {
  14. poll(callback); // retry on timeout
  15. NEXT_RETRY = 5;
  16. return;
  17. }
  18. var resp = null
  19. ,success = Math.floor(xhr.status / 100) === 2;
  20. if (success) {
  21. NEXT_RETRY = 5;
  22. resp = xhr.response;
  23. try {
  24. resp = JSON.parse(resp);
  25. } catch (e) {
  26. resp = null;
  27. }
  28. } else {
  29. NEXT_RETRY += Math.floor(NEXT_RETRY /2);
  30. NEXT_RETRY = Math.min(60, NEXT_RETRY);
  31. }
  32. callback(success, resp);
  33. }
  34. };
  35. xhr.open('GET', 'api?t=' +SLACK.lastServerVersion, true);
  36. xhr.send(null);
  37. }
  38. /**
  39. * @param {boolean} success
  40. * @param {*} response
  41. **/
  42. function onPollResponse(success, response) {
  43. if (success) {
  44. if (response) {
  45. SLACK.update(response);
  46. }
  47. startPolling();
  48. } else {
  49. setTimeout(startPolling, NEXT_RETRY * 1000);
  50. }
  51. }
  52. function startPolling() {
  53. poll(onPollResponse);
  54. }