需求:做一个红绿灯组件,绿灯亮10秒,黄灯亮5秒,红灯亮2秒,循环往复

    1. //先写一个高亮工具函数
    2. function lightenTool(lightType){
    3. const lightDomArr= [...document.getElementsByClass('lights')],
    4. currentLight = document.getElementsByClass(lightType)[0];
    5. //先清除所有元素高亮类名
    6. lightDomArr.forEach((elem)=>{
    7. elem.classList.remove('lighten')
    8. })
    9. //给当前颜色信号灯添加高亮类名
    10. currentLight.classList.add('lighten')
    11. cosnole.log(lightType)
    12. }
    13. // 1、传统递归不嵌套方法
    14. funcion lightsGo(){
    15. lightenTool('green')
    16. setTimeout(function(){
    17. lightenTool('yellow')
    18. },10000)
    19. setTimeout(function(){
    20. lightenTool('red')
    21. lightsGo()
    22. },15000)
    23. setTimeout(function(){
    24. lightsGo()
    25. },17000)
    26. }
    27. //2、传统回调嵌套方法,复杂、难维护
    28. function lightsGo(){
    29. lightenTool('green')
    30. setTimeout(function(){
    31. lightenTool('yellow')
    32. setTimeout(function(){
    33. lightenTool('red')
    34. setTimeout(function(){
    35. lightsGo()
    36. },2000)
    37. },5000)
    38. },10000)
    39. }
    40. //3、promise链式调用
    41. function lightenTool(type){
    42. console.log(type)
    43. }
    44. function sleep(time){
    45. return new Promise((resolve)=>{
    46. setTimeout(()=>{
    47. resolve()
    48. },time)
    49. })
    50. }
    51. //function promiseResolve(callback,time){
    52. // return new Promise((resolve)=>{
    53. // setTimeout(()=>{
    54. // console.log(callback)
    55. // resolve()
    56. // },time)
    57. // })
    58. //}
    59. // 这个函数没有遵循单一功能原则,把回调函数和异步等待功能耦合在一起,对后续使用造成了困难
    60. function lightsGo(){
    61. lightenTool('green');
    62. sleep(10000)
    63. .then(()=>{
    64. lightenTool('yellow');
    65. return sleep(5000)
    66. })
    67. .then(()=>{
    68. lightenTool('red');
    69. return sleep(2000)
    70. })
    71. .then(()=>{
    72. lightsGo()
    73. })
    74. }
    75. lightsGo()
    76. //3.async和await同步写法
    77. function lightenTool(type){
    78. console.log(type)
    79. }
    80. function sleep(time){
    81. return new Promise((resolve)=>{
    82. setTimeout(()=>{resolve()},time)
    83. })
    84. }
    85. async function lightsGo(){
    86. lightenTool('green')
    87. await sleep(10000);
    88. lightenTool('yellow')
    89. await sleep(5000);
    90. lightenTool('red')
    91. await sleep(2000);
    92. lightsGo()
    93. }
    94. //还可以改进用while do来写,不用递归
    95. async function lightsGo(){
    96. while(true){
    97. lightenTool('green')
    98. await sleep(10000);
    99. lightenTool('yellow')
    100. await sleep(5000);
    101. lightenTool('red')
    102. await sleep(2000);
    103. }
    104. }