scheduler.js 1.6 KB

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