1

例:
obj.write("1").await(1000).write("2");
// 打印 1
// 等待 await 时长之后打印 2### 题目描述

Jogen 2
1月18日提问
4 个回答
5

  class Obj {
    constructor () {
      this.sleep = 0
    }

    write (str) {
      if (this.sleep) {
        setTimeout(() => {
            console.log(str)
          },
          this.sleep)
      } else {
        console.log(str)
      }
      return this
    }

    await (time) {
      this.sleep += time
      return this
    }
  }

  const obj = new Obj()

  obj.write('1').await(1000).write('2').await(3000).write(3)
2

虽然 BeliefRC 的代码没什么大问题, 符合你的要求, 我还是当成练手写两个实现, 你比较一下.

  1. 利用Promise, 这个就简单了
function write(str){
    this.next.then(function(){
        console.log(str)
    })
    return this;
}

function await(time){
    return getObj(time,this);
}

function getSleep(time){
    return function(){
        return new Promise(ok=>setTimeout(ok,time))
    }
}

function getObj(time,obj){
    return {
        write,
        await,
        next : obj ? obj.next.then(getSleep(time)) : getSleep(time)()
    }
}
var obj = getObj(0);
obj.write("1").await(1000).write("2").write('3').await(1000).write(4);
obj.write("11").await(1000).write("22").write('33').await(1000).write(44); //测试并行情况
  1. 不用Promise稍微麻烦一点
function Obj(time,parent){
    var self = this;
    this._events = [];
    this._done = false;
    var _init = function(){
        setTimeout(function(){
            self._done = true;
            while (self._events.length > 0) {
                var work = self._events.shift();
                self[work[0]].apply(self,work[1]);
            }
        },time);
    }
    if(parent){
        parent.done(_init)
    }else{
        _init()
    }
}

Obj.prototype = {
    await: function(time){
        return new Obj(time,this);
    },
    write: function(str){
        if(this._done){
            console.log(str);
        }else{
            this._events.push(['write',[str]])
        }
        return this;
    },
    done: function(fn){
        if(this._done){
            fn();
        }else{
            this._events.push(['done',[fn]])
        }
        return this;
    }
}

var obj = new Obj(0);
obj.write("1").await(1000).write("2").write('3').await(1000).write(4);
obj.write("11").await(1000).write("22").write('33').await(1000).write(44); //测试并行情况
1
function Delay() {
    this.queue = Promise.resolve();
}
Delay.prototype.write = function() {
    var args = arguments;
    var _this = this;
    this.queue = this.queue.then(function() {
        console.log.apply(_this, args);
    });
    return this;
};
Delay.prototype.await = function(time) {
    this.queue = this.queue.then(function() {
        return new Promise(function(resolve) {
            setTimeout(resolve, time);
        });
    });
    return this;
};
var obj = new Delay();
obj.write("1").await(1000).write("2");
0

就两次么 还是无限

撰写答案

推广链接