Skip to content

先执行方法A( ), 间隔0.5秒后, 再执行方法B( ), 再间隔0.5秒后,执行方法A( ),如此循环执行 #14

Open
@ScoutYin

Description

@ScoutYin
// 参数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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions