JS中如何实现函数队列?

var stack = [];

// 定义 index 和 next
var index = 0;

function next(){
    var fn = stack[index];
    index = index + 1;
    if ( typeof fn == 'function' ){
         fn();
    }
}

function fn1(){
    console.log('第一个调用');
    next(); // stack 中每一个函数都必须调用`next`
}

stack.push(fn1);

function fn2() {
    setTimeout(function(){
        console.log('第二个被调用');
        next();
    }, 0)
}

stack.push(fn2, function(){
    console.log('第三个调用');
    next();
})

next();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容