workflow.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 = 1000 * 60 * 1; // 3 min timeout
  10. xhr.onreadystatechange = function(e) {
  11. if (xhr.readyState === 4) {
  12. if (xhr.status === 0) {
  13. poll(callback); // retry on timeout
  14. NEXT_RETRY = 5;
  15. return;
  16. }
  17. var resp = null
  18. ,success = Math.floor(xhr.status / 100) === 2;
  19. if (success) {
  20. NEXT_RETRY = 5;
  21. resp = xhr.response;
  22. try {
  23. resp = JSON.parse(resp);
  24. } catch (e) {
  25. resp = null;
  26. }
  27. } else {
  28. NEXT_RETRY += Math.floor(NEXT_RETRY /2);
  29. NEXT_RETRY = Math.min(60, NEXT_RETRY);
  30. }
  31. callback(success, resp);
  32. }
  33. };
  34. xhr.open('GET', 'api?v=' +SLACK.lastServerVersion, true);
  35. xhr.send(null);
  36. }
  37. /**
  38. * @param {boolean} success
  39. * @param {*} response
  40. **/
  41. function onPollResponse(success, response) {
  42. if (success) {
  43. if (response) {
  44. SLACK.update(response);
  45. }
  46. startPolling();
  47. } else {
  48. setTimeout(startPolling, NEXT_RETRY * 1000);
  49. }
  50. }
  51. function startPolling() {
  52. poll(onPollResponse);
  53. }