对象的sleep方法,链式调用时后面方法指定时间调用

193 阅读1分钟

前端时间看到一个面试题 题目是:

const boy = new PlayBoy('Tom');
boy.sayHi().sleep(1000).play('王者').sleep(2000).play('跳一跳')
// 输出
// 大家好我是Tom
// 1s 之后
// 我在玩王者
// 2s 之后
// 我在玩跳一跳

在线运行地址:js.jsrun.net/7aPKp/edit

记录一下 自己的实现方法

  • 首先创建自己的构造函数
function PlayBoy(name) {
    this.name = name;
    this.stack = []
}
  • sayHi方法
PlayBoy.prototype.sayHi = function () {
    console.log('大家好我是' + this.name)
    return this;
}
  • pushStack 方法
PlayBoy.prototype.pushStack = function (fn) {
    this.stack.push(fn)
}
  • sleep 方法
PlayBoy.prototype.sleep = function (time) {
    this.pushStack(() => {
        console.log('开始睡眠1s', Date.now())
        setTimeout(() => {
            console.log('醒来', Date.now())
            const fn = this.stack.shift()
            if (fn) {
                fn()
            }
        }, time)
    })
    if (this.stack.length == 1) {
        this.stack.shift()()
    }
    return this;
}
  • play 方法
PlayBoy.prototype.play = function (game) {
    this.pushStack(() => {
        console.log(`我在玩${game}`)
        const fn = this.stack.shift()
        if (fn) {
            fn()
        }
    })
    return this;
}