涉及的知识点:
- 流程控制:创建task任务队列,使用push、shift、unshift方法操作任务
- 闭包:当闭包中的值引用自闭包外部,那么这些值会始终存放在内存中。下面例子中的
name
、time
都会保存在内存中,不至于访问时为undefined
function _lazyMan (name) {
// 创建一个任务队列
this.task = [];
let self = this;
let fn = (function (name) {
return function () {
console.log(`Hi! This is ${name}!`);
// 执行下一个任务
self.next();
};
})(name);
this.task.push(fn);
// 在下一个事件循环启动任务
setTimeout(function () {
self.next();
}, 0);
}
_lazyMan.prototype.next = function () {
let fn = this.task.shift();
fn && fn();
};
_lazyMan.prototype.sleepFirst = function (time) {
let self = this;
let fn = (function (time) {
return function () {
setTimeout(function () {
console.log(`Wake up after ${time}s!`);
self.next();
}, time * 1000);
}
})(time);
this.task.unshift(fn);
return this;
}
_lazyMan.prototype.sleep = function (time) {
let self = this;
let fn = (function (time) {
return function () {
setTimeout(function () {
console.log(`Wake up after ${time}s!`);
self.next();
}, time * 1000);
}
})(time);
this.task.push(fn);
return this;
}
_lazyMan.prototype.eat = function (name) {
let self = this;
let fn = (function (name) {
return function () {
console.log(`Eat ${name}~`)
self.next();
}
})(name);
this.task.push(fn);
}
function lazyMan (name) {
return new _lazyMan(name);
}
lazyMan('17khba').sleepFirst(10).eat('lunch');