xapi-connector
Version:
Simple low level connector for xAPI written in Coffeescript
65 lines (54 loc) • 1.54 kB
JavaScript
// Generated by CoffeeScript 1.8.0
/*
The Dispatcher class.
It takes asynchronous requests to send something through the stream
and sends it asynchronously in intervals.
*/
(function() {
var Dispatcher;
Dispatcher = (function() {
function Dispatcher(stream, delay, max_sins) {
this.stream = stream;
this.delay = delay != null ? delay : 0;
this.max_sins = max_sins != null ? max_sins : 0;
this._que = [];
this._last = 0;
this._clearing_que = false;
this._sins = 0;
}
Dispatcher.prototype.add = function(msg) {
this._que.push(msg);
if (this._clearing_que === false) {
this._clearQue();
}
};
Dispatcher.prototype.getQue = function() {
return this._que;
};
Dispatcher.prototype._clearQue = function() {
var diff, msg;
this._clearing_que = true;
diff = new Date().getTime() - this._last;
if (diff > this.delay || this._sins < this.max_sins) {
this.stream.write(msg = this._que.shift());
this._last = new Date().getTime();
if (diff > this.delay) {
if (this._sins > 0) {
this._sins -= 1;
}
} else {
this._sins += 1;
}
if (this._que.length > 0) {
this._clearQue();
} else {
this._clearing_que = false;
}
} else {
setTimeout(this._clearQue.bind(this), this.delay + 1 - diff);
}
};
return Dispatcher;
})();
module.exports = Dispatcher;
}).call(this);