美文网首页
尝试写了一个队列

尝试写了一个队列

作者: 未來Miral | 来源:发表于2018-07-18 10:28 被阅读0次
    class setQueue{
        constructor(fn){
            this.fn = fn;
            this.lists = new Array();
            this.state = true;
        }
        add(data){
            this.lists.push(() => {
                this.fn(data, () => {
                   this.lists.shift();
                   this.state = true;
                   setTimeout(() => {
                        this.run();
                    }, 500);
                });
            });
            this.run();
        }
        run(){
            if (this.state){
                if (this.lists[0]){
                    this.state = false;
                    this.lists[0]();
                }
            }
        }
    }
    

    方法调用

    
    let setChant = new setQueue(test); // 实例化
    var a = 0;
    function test(a,callback) {
          let timer = setInterval(() => {
               if (a < 10) {
                      console.log(a);
                      a++;
                }
                else{
                        clearInterval(timer);
                        if(callback){
                            callback();
                         }
                 }
           }, 1000);
    }
    setChant.add(a); // 调用
    

    相关文章

      网友评论

          本文标题:尝试写了一个队列

          本文链接:https://www.haomeiwen.com/subject/pwtopftx.html