Skip to content

Instantly share code, notes, and snippets.

@MaBecker
Last active April 5, 2019 11:17
Show Gist options
  • Save MaBecker/9bb0a825a491a0760f17ecc3264232dc to your computer and use it in GitHub Desktop.
Save MaBecker/9bb0a825a491a0760f17ecc3264232dc to your computer and use it in GitHub Desktop.
/*
function queue
based on
https://stackoverflow.com/questions/17528749/semaphore-like-queue-in-javascript/17528961#17528961
*/
var Queue = (function(){
function Queue(autorun) {
if (typeof autorun !== "undefined") {
this.autorun = autorun;
}
this.queue = []; //initialize the queue
}
Queue.prototype.autorun = true;
Queue.prototype.running = false;
Queue.prototype.queue = [];
Queue.prototype.add = function(callback) {
var _this = this;
//add callback to the queue
this.queue.push(function() {
var finished = callback();
if (typeof finished === "undefined" || finished) {
// if callback returns `false`, then you have to
// call `next` somewhere in the callback
_this.dequeue();
}
});
if (this.autorun && !this.running) {
// if nothing is running, then start the engines!
this.dequeue();
}
return this; // for chaining fun!
};
Queue.prototype.dequeue = function() {
this.running = false;
//get the first element off the queue
var shift = this.queue.shift();
if (shift) {
this.running = true;
shift();
}
return shift;
};
Queue.prototype.next = Queue.prototype.dequeue;
return Queue;
})();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var fqueue = new Queue();
function say(msg,cb){
console.log('say:',msg);
cb();
}
function shout(msg,cb){
console.log('shout:',msg);
}
function wisper(msg,cb){
console.log('wisper:',msg);
}
function cb(){
console.log('done');
}
fqueue.add(function(){say('hello',cb);});
setTimeout(function(){
fqueue.add(function(){shout('Hey');});
},1000);
setTimeout(function(){
fqueue.add(function(){wisper('can you hear me?');});
},2000);
setTimeout(function(){
for (i=0;i<50;i++){
fqueue.add(function(){say('job id='+ i.toString(),cb);});
}
},3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment