尝试写了一个队列

2018-07-18  本文已影响0人  未來Miral
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); // 调用
上一篇下一篇

猜你喜欢

热点阅读