sync/lib/asyncqueue.js

55 lines
1.0 KiB
JavaScript
Raw Normal View History

2013-09-29 05:27:43 +00:00
var AsyncQueue = function () {
this._q = [];
this._lock = false;
this._tm = 0;
};
AsyncQueue.prototype.next = function () {
if (this._q.length > 0) {
if (!this.lock())
return;
2013-09-29 16:30:36 +00:00
var item = this._q.shift();
var fn = item[0], tm = item[1];
this._tm = Date.now() + item[1];
2013-09-29 05:27:43 +00:00
fn(this);
}
};
AsyncQueue.prototype.lock = function () {
2013-09-29 16:30:36 +00:00
if (this._lock) {
if (this._tm > 0 && Date.now() > this._tm) {
this._tm = 0;
return true;
}
2013-09-29 05:27:43 +00:00
return false;
2013-09-29 16:30:36 +00:00
}
2013-09-29 05:27:43 +00:00
this._lock = true;
return true;
};
AsyncQueue.prototype.release = function () {
var self = this;
if (!self._lock)
return false;
self._lock = false;
2013-09-29 16:30:36 +00:00
setImmediate(function () {
2013-09-29 05:27:43 +00:00
self.next();
});
return true;
};
AsyncQueue.prototype.queue = function (fn) {
var self = this;
2013-09-29 16:30:36 +00:00
self._q.push([fn, 20000]);
2013-09-29 05:27:43 +00:00
self.next();
};
AsyncQueue.prototype.reset = function () {
this._q = [];
this._lock = false;
};
2013-09-29 16:30:36 +00:00
module.exports = AsyncQueue;