Skip to content

Instantly share code, notes, and snippets.

@vincenting
Created November 24, 2014 15:43
Show Gist options
  • Select an option

  • Save vincenting/e4bff7e65d617c5313c9 to your computer and use it in GitHub Desktop.

Select an option

Save vincenting/e4bff7e65d617c5313c9 to your computer and use it in GitHub Desktop.
Delay queue for javascript.
$.queue = function(queue) {
var q = queue.sort(function(a, b) {
return a.delay - b.delay;
}),
next, pre = {
delay: 0
};
var run = function() {
next = q.shift();
if (!next) return;
setTimeout(function() {
next.fn();
pre = next;
return run();
}, next.delay - pre.delay);
};
return {
run: run
};
}
$.queue([{
delay: 1000,
fn: function() {
console.log('1---')
}
}, {
delay: 3000,
fn: function() {
console.log('2---')
}
}, {
delay: 2000,
fn: function() {
console.log('3---')
}
}]).run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment