SOURCE

/**
 * 
    实现一个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
     
    以此类推。
 * 
 */

function LazyMan(name) {
    let man = {
        name: name,
        tasks: [['introduce']],
        beginWithSleep: false,
        sleep: function (sec) {
            this.tasks.push(['sleep', sec]);
            return this;
        },
        sleepFirst: function (sec) {
            this.tasks.shift();
            this.tasks.push(['sleep', sec]);
            this.tasks.push(['introduce']);
            return this;
        },
        eat: function (kind) {
            this.tasks.push(['eat', kind]);
            return this;
        },
        do: function() {
            if (this.tasks.length === 0) {
                return;
            }
            const task = this.tasks.shift();
            if (task[0] === 'introduce') {
                console.log(`Hi! This is ${this.name}`);
                this.do();
            } else if (task[0] === 'sleep') {
                setTimeout(() => {
                    console.log(`Wake up after ${task[1]}`);
                    this.do();
                }, task[1] * 1000);
            } else if (task[0] === 'eat') {
                console.log(`Eat ${task[1]}~`);
                this.do();
            }
        }
    };

    // 让 man.do 加到宏任务队列队尾,使添加 task 先执行
    setTimeout(function() {
        man.do();
    }, 0);
    
    return man;
}

// LazyMan("Hank");
// LazyMan("Hank").sleepFirst(5).eat("supper");
// LazyMan("Hank").eat("dinner").eat("supper");
// LazyMan("Hank").sleep(1).eat("dinner");
console 命令行工具 X clear

                    
>
console