Skip to content

Instantly share code, notes, and snippets.

@zhjgithub
Created November 22, 2017 02:33
Show Gist options
  • Save zhjgithub/aa8865657f61330ef393e8cda4c99f09 to your computer and use it in GitHub Desktop.
Save zhjgithub/aa8865657f61330ef393e8cda4c99f09 to your computer and use it in GitHub Desktop.
function delay(fn, t) {
// private instance variables
var queue = [], self, timer;
function schedule(fn, t) {
timer = setTimeout(function() {
timer = null;
fn();
if (queue.length) {
var item = queue.shift();
schedule(item.fn, item.t);
}
}, t);
}
self = {
delay: function(fn, t) {
// if already queuing things or running a timer,
// then just add to the queue
if (queue.length || timer) {
queue.push({fn: fn, t: t});
} else {
// no queue or timer yet, so schedule the timer
schedule(fn, t);
}
return self;
},
cancel: function() {
clearTimeout(timer);
queue = [];
}
};
return self.delay(fn, t);
}
function log1() {
log("Message 1");
}
function log2() {
log("Message 2");
}
function log3() {
log("Message 3");
}
var d = delay(log1, 500)
.delay(log2, 700)
.delay(log3, 600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment