SOURCE

// 设计LazyMan类
// LazyMan('Tony')
// Hi I am Tony

// LazyMan('Tony').sleep(2).eat('lunch')
// Hi I am Tony
// 等待2秒
// I am eating lunch

// LazyMan('Tony').eat('lunch').sleep(2).eat('dinner')
// LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(2).sleep(3).eat('junk food')
// I am Tony
// 等待2秒
// 继续顺序执行

class LazyManClass {
    constructor(name) {
        console.log(`Hi I am ${name}`)
        this.queue = []
        setTimeout(() => {
            this.next()
        }, 0)
    }
    sleep(delay) {
        const that = this
        const fn = () => {
            setTimeout(() => {
                console.log(`等待${delay}秒`)
                this.next()
            }, delay * 1000)
        }
        this.queue.push(fn)
        return this
    }
    eat(x) {
        const fn = () => {
            console.log(`I am eating ${x}`)
            this.next()
        }
        this.queue.push(fn)
        return this
    }
    next() {
        const fn = this.queue.shift()
        fn && fn()
    }
}

function LazyMan(name) {
    return new LazyManClass(name)
}

LazyMan('Tony').eat('lunch').sleep(3).eat('dinner')
console 命令行工具 X clear

                    
>
console