Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ScoutYin opened this issue May 25, 2018 · 0 comments
Labels
JavaScript 基础 About JavaScript

Comments

@ScoutYin
Copy link
Owner

// 参数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)
@ScoutYin ScoutYin added the JavaScript 基础 About JavaScript label May 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 基础 About JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant