1. callback方法

  1. function red() {
  2. console.log('red');
  3. }
  4. function green() {
  5. console.log('green');
  6. }
  7. function yellow() {
  8. console.log('yellow');
  9. }
  1. function lightToggle(fn, timer, callback) {
  2. setTimeout(() => {
  3. if (fn === 'red') {
  4. red()
  5. }
  6. else if (fn === 'green') {
  7. green()
  8. }
  9. else if (fn === 'yellow') {
  10. yellow()
  11. }
  12. callback()
  13. }, timer)
  14. }
  15. function a() {
  16. lightToggle("red", 3000, b)
  17. }
  18. function b() {
  19. lightToggle("yellow", 2000, c)
  20. }
  21. function c() {
  22. lightToggle("green", 1000, a)
  23. }
  24. a()

2. promise方法

  1. // 使用promise实现
  2. function task(light, delay) {
  3. return new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. if (light === 'red') {
  6. red()
  7. }
  8. else if (light === 'green') {
  9. green()
  10. }
  11. else if (light === 'yellow') {
  12. yellow()
  13. }
  14. resolve()
  15. }, delay)
  16. })
  17. }
  18. async function task_all() {
  19. await task('red', 3000)
  20. await task('yellow', 2000)
  21. await task('green', 1000)
  22. task_all()
  23. }
  24. task_all()
  25. // const step = () => {
  26. // task('red', 3000)
  27. // .then(() => task('yellow', 2000))
  28. // .then(() => task('green', 1000))
  29. // .then(step)
  30. // }
  31. // step()