scheduler.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var _tslib = require('./_virtual/_tslib.js');
  4. var defaultOptions = {
  5. deferEvents: false
  6. };
  7. var Scheduler =
  8. /*#__PURE__*/
  9. /** @class */
  10. function () {
  11. function Scheduler(options) {
  12. this.processingEvent = false;
  13. this.queue = [];
  14. this.initialized = false;
  15. this.options = _tslib.__assign(_tslib.__assign({}, defaultOptions), options);
  16. }
  17. Scheduler.prototype.initialize = function (callback) {
  18. this.initialized = true;
  19. if (callback) {
  20. if (!this.options.deferEvents) {
  21. this.schedule(callback);
  22. return;
  23. }
  24. this.process(callback);
  25. }
  26. this.flushEvents();
  27. };
  28. Scheduler.prototype.schedule = function (task) {
  29. if (!this.initialized || this.processingEvent) {
  30. this.queue.push(task);
  31. return;
  32. }
  33. if (this.queue.length !== 0) {
  34. throw new Error('Event queue should be empty when it is not processing events');
  35. }
  36. this.process(task);
  37. this.flushEvents();
  38. };
  39. Scheduler.prototype.clear = function () {
  40. this.queue = [];
  41. };
  42. Scheduler.prototype.flushEvents = function () {
  43. var nextCallback = this.queue.shift();
  44. while (nextCallback) {
  45. this.process(nextCallback);
  46. nextCallback = this.queue.shift();
  47. }
  48. };
  49. Scheduler.prototype.process = function (callback) {
  50. this.processingEvent = true;
  51. try {
  52. callback();
  53. } catch (e) {
  54. // there is no use to keep the future events
  55. // as the situation is not anymore the same
  56. this.clear();
  57. throw e;
  58. } finally {
  59. this.processingEvent = false;
  60. }
  61. };
  62. return Scheduler;
  63. }();
  64. exports.Scheduler = Scheduler;