UNPKG

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