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

71 lines
2.1 KiB
JavaScript

"use strict";
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
var defaultOptions = {
deferEvents: false
};
var Scheduler = /** @class */ (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;
}());
exports.Scheduler = Scheduler;
//# sourceMappingURL=scheduler.js.map