主要的难点在于理解
1. 如何判断Lazyman对象的方法被调用结束(也就是简单的setTimeout()函数所实现的功能)
2. 如何实现next()函数
function _lazyMan (name) {
this.tasks = [];
var self = this;
var fn = (function(name){
return function () {
console.log('hi ' + name);
self.next();
}
})(name);
this.tasks.push(fn);
setTimeout(function () {
self.next();
}, 0); // 下一个事件循环启动
}
// 事件调度函数
_lazyMan.prototype.next = function () {
var fn = this.tasks.shift();
fn && fn();
}
_lazyMan.prototype.eat = function (name) {
var self = this;
var fn = (function(name){
return function() {
console.log('eat ' + name)
self.next();
}
})(name);
this.tasks.push(fn);
return this;
}
_lazyMan.prototype.sleep = function (time) {
var self = this;
var fn =(function (time) {
return function() {
setTimeout(function () {
console.log('sleeped ' + time + ' s')
self.next();
}, time*1000);
}
})(time);
this.tasks.push(fn);
return this;
}
_lazyMan.prototype.sleepFirst = function (time) {
var self = this;
var fn =(function (time) {
return function() {
setTimeout(function () {
console.log('sleeped' + time + 's')
self.next();
}, time*1000);
}
})(time);
this.tasks.unshift(fn);
return this;
}
function lazyMan(name) {
return new _lazyMan(name);
}
lazyMan('sjn').sleepFirst(2).eat('meal')
结果:
// 先停顿两秒
sleeped 2 s
hi sjn
eat meal
lazyMan('sjn').sleep(2).eat('meal')
结果:
hi sjn
// 停顿两秒
sleep 2 s
eat meal