Skip to content

Instantly share code, notes, and snippets.

@cemerson
Created August 28, 2012 00:59
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 cemerson/3493995 to your computer and use it in GitHub Desktop.
Save cemerson/3493995 to your computer and use it in GitHub Desktop.
Javascript: Delayed Function Queue
/* Core Methods */
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
/* Test code: */
var queueStart = +new Date();
var q = new TimedQueue(2000);
q.add(function(){
console.log('hey');
console.log(+new Date() - queueStart);
});
q.add(function(){
console.log('ho');
console.log(+new Date() - queueStart);
}, 3000);
quickMode.add(function(){
console.log('bye');
console.log(+new Date() - queueStart);
});
q.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment