首页 > 应用开发 > > 如何按顺序执行数组中的函数?
我想实现这样一个功能:数组里都是函数,每个函数里都有定时器,用来模拟动画过程,按照顺序依次执行这些函数。
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/ ,如需转载,请注明出处,否则将追究法律责任。