- es5 实现
function log1() {
console.log("message 1")
}
function log2() {
console.log("message 2")
}
function log1() {
console.log("message 3")
}
function delay(fn, ms) {
var timer, self;
var queue
function schedule(fn, ms) {
timer = setTimeout(function() {
timer = null
fn()
if (queue.length) {
var item = queue.shift(item)
schedule(item.fn, item.ms)
}
}, ms)
}
self = {
delay: function(fn, ms) {
if (queue,length || timer) {
queue.push({fn, ms})
} else {
schedule(fn, ms)
}
return self;
},
cancel: function() {
clearTimeout(timer)
queue = []
}
}
return self.delay(fn, ms)
}
var d = dalay(log1, 500).delay(log2, 1000).delay(log3, 2000)
- es6 实现
function log1() {
console.log("message 1")
}
function log2() {
console.log("message 2")
}
function log1() {
console.log("message 3")
}
function delay(fn, ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
Promise.delay = function(fn, ms) {
// fn is optional
if (!ms) {
ms = fn
fn = function() {}
}
return delay(fn, ms).then(fn)
}
Promise.prototype.delay = function (fn, ms) {
return this.then(() => {
return Promise.delay(fn, ms)
})
}
Promise.delay(log1, 500).delay(log2, 2000).delay(log3, 3000);
// 使用async/await 优化
async queueTask() {
await Promise.delay(log1, 500)
await Promise.delay(log2, 1500)
await Promise.delay(log3, 2500)
}
queueTask()