ITPub博客

首页 > 应用开发 > > 如何按顺序执行数组中的函数?

如何按顺序执行数组中的函数?

作者:hawkliu 时间:2019-08-12 13:47:02 0 删除 编辑

我想实现这样一个功能:数组里都是函数,每个函数里都有定时器,用来模拟动画过程,按照顺序依次执行这些函数。

let num = 0;

            function a(){
                setTimeout(function(){
                    console.log(1);
                    num++;
                }, 2000);
            };

            function b(){
                setTimeout(function(){
                    console.log(2);
                    num++;
                }, 3000);
            };

            function c(){
                setTimeout(function(){
                    console.log(3);
                    num++;
                }, 1000);
            };

            let arr = [a, b, c];

            arr.forEach((fn, index) => {
                if(num === index){
                    //num 等于下标时,才能执行相应的函数
                    fn();
                }
            });

这样写的话只有 a 可以执行,请高手赐教

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/887/viewspace-3150120/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-29

  • 博文量
    274
  • 访问量
    1129