Files
30-seconds-of-code/node_modules/xstate/es/scheduler.js
2019-08-20 15:52:05 +02:00

66 lines
2.0 KiB
JavaScript

var __assign = this && this.__assign || function () {
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var defaultOptions = {
deferEvents: false
};
var Scheduler = /** @class */ /*#__PURE__*/function () {
function Scheduler(options) {
this.processingEvent = false;
this.queue = [];
this.initialized = false;
this.options = __assign({}, defaultOptions, options);
}
Scheduler.prototype.initialize = function (callback) {
this.initialized = true;
if (callback) {
if (!this.options.deferEvents) {
this.schedule(callback);
return;
}
this.process(callback);
}
this.flushEvents();
};
Scheduler.prototype.schedule = function (task) {
if (!this.initialized || this.processingEvent) {
this.queue.push(task);
return;
}
if (this.queue.length !== 0) {
throw new Error('Event queue should be empty when it is not processing events');
}
this.process(task);
this.flushEvents();
};
Scheduler.prototype.flushEvents = function () {
var nextCallback = this.queue.shift();
while (nextCallback) {
this.process(nextCallback);
nextCallback = this.queue.shift();
}
};
Scheduler.prototype.process = function (callback) {
this.processingEvent = true;
try {
callback();
} catch (e) {
// there is no use to keep the future events
// as the situation is not anymore the same
this.queue = [];
throw e;
} finally {
this.processingEvent = false;
}
};
return Scheduler;
}();
export { Scheduler };
//# sourceMappingURL=scheduler.js.map