js实现队列-通过闭包方式

需求:

// 实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)
/* 输出: 
Hi! This is Hank!
*/

LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
/* 输出: 
Hi! This is Hank!
// 等待10秒..
Wake up after 10
Eat dinner~
*/

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)
/* 输出: 
Hi This is Hank!
Eat dinner~
Eat supper~
*/

LazyMan(“Hank”).sleepFirst(5).eat(“supper”)
/* 等待5秒,输出
Wake up after 5
Hi This is Hank!
Eat supper
*/

// 以此类推。

实现:

var LazyMan = function(name) {  
    var queue = [];
    var sayHi = function() {
      console.log('Hi! This is ' + name + '!');
      self.next();
    }
    queue.push(sayHi);
    setTimeout(function(){
      self.next();
    }, 0);
    var self = {
      next: function() {
        if (queue.length) {
          var fn = queue.shift();
          if (typeof fn === 'function') {
            fn();
          }
        }
      },
      sleep: function(time) {
        queue.push(function() {
          setTimeout(function() {
            console.log('Wake up after ' + time);
            self.next();
          }, time * 1000);
        });
        return this;
      },
      eat: function(meal) {
        queue.push(function() {
          console.log('Eat ' + meal + '~');
          self.next();
        });
        return this;
      },
      sleepFirst: function(time) {
        queue.unshift(function() {
          setTimeout(function() {
            console.log('Wake up after ' + time);
            self.next();
          }, time * 1000);
        });
        return this;
      },
    }
    return self;
}

分析:

待完成...

原文地址:https://www.cnblogs.com/fanfan-code/p/6398467.html