Open
Description
// 参数1:需要循环执行的函数数组; 参数2:执行的时间间隔
const doLoop = (fns, interval) => {
let step = 0
const excu = (fn) => {
if (typeof fn !== 'function') {
throw new Error(`'${fn}' is not a function`)
}
setTimeout(() => {
fn()
++step
if (step >= fns.length) {
// 使用setTimeout避免栈溢出
setTimeout(() => {
doLoop(fns, interval)
}, interval)
} else {
excu(fns[step])
}
}, step === 0 ? 0 : interval)
}
excu(fns[0])
}
// test
const A = () => {
console.log('A')
}
const B = () => {
console.log('B')
}
const C = () => {
console.log('C')
}
const D = () => {
console.log('D')
}
doLoop([A, B, C, D], 500)