Skip to content

Instantly share code, notes, and snippets.

@shripadk
Created December 15, 2011 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shripadk/1482647 to your computer and use it in GitHub Desktop.
Save shripadk/1482647 to your computer and use it in GitHub Desktop.
queue
ZQueue = function() {
this.queue = [];
this.queued = false;
};
ZQueue.prototype.dequeue = function() {
this.queued = false;
this.shiftQueue();
};
ZQueue.prototype.enqueue = function(fn_to_execute) {
// no items in queue
if(!this.queued) {
this.queued = true;
fn_to_execute();
} else {
// queue item to run later
this.queue.push(fn_to_execute);
}
};
ZQueue.prototype.shiftQueue = function() {
if(this.queue.length) {
this.queued = true;
var fn_to_execute = this.queue.shift();
fn_to_execute();
}
};
ZQueue.prototype.flushQueue = function() {
var len = this.queue.length;
while(len--) {
this.dequeue();
}
};
@shripadk
Copy link
Author

for loop without queue:

    var count = 0; for(var i=0; i<100; i++) { setTimeout(function() { console.log(count++); }, 10 )  }

for loop with queue:

   var que = new ZQueue();
   var count = 0; for(var i=0; i<100; i++) { que.enqueue(function() { setTimeout(function() { console.log(count++); que.dequeue(); }, 10 ) }); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment