Skip to content

手写顺序打印sleep

实现方法满足,每隔3000ms打印内容: person.console('breakfast').sleep(3000).console('lunch').sleep(3000).console('dinner')

js
class Person {
    constructor() {
        this.tasks=[]
        setTimeout(() => {
            this.next()
        })
    }
    
    next() {
        let task = this.tasks.shift()
        task && task()
    }
    
     console(str) {
        let t = () => {
            console.log(str)
            this.next()
        }
         this.tasks.push(t)
         return this
     }

    sleep(wait) {
        let t = () => setTimeout(() => {
            this.next()
        }, wait)
         this.tasks.push(t)
         return this
     }
}
// 测试
new Person().console('breakfast').sleep(3000).console('lunch').sleep(3000).console('dinner')