Created
November 22, 2017 02:33
-
-
Save zhjgithub/aa8865657f61330ef393e8cda4c99f09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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