Javascript怎么实现红绿灯

 4693

javascript实现红绿灯的方法:1、使用setTimeout和递归来实现循环改变颜色;2、使用Promise,并把下一次的颜色改变写在then里面;3、使用async await和while实现红绿灯效果。


Javascript怎么实现红绿灯


JavaScript 实现红绿灯

使用setTimeout、Promise、async await 三种方式实现红绿灯代码,红灯2秒,黄灯1秒,绿灯3秒,循环改变颜色。改变颜色的方法,就简单写成打印出颜色。


setTimeout实现

使用setTimeout是最基本的实现方式,代码如下,使用递归来实现循环改变颜色。

  1. function changeColor(color) {
  2.     console.log('traffic-light ', color);
  3. }
  4. function main() {
  5.     changeColor('red');
  6.     setTimeout(()=>{
  7.         changeColor('yellow');
  8.         setTimeout(() => {
  9.             changeColor('green');
  10.             setTimeout(main, 2000);
  11.         }, 1000);
  12.     }, 2000);
  13. }
  14. main();


Promise 实现

使用Promise,把下一次的颜色改变写在then里面,最后同样使用递归完成循环。

  1. function sleep(duration){
  2.     return new Promise(resolve => {
  3.         setTimeout(resolve, duration);
  4.     })
  5. }
  6. function changeColor(duration,color){
  7.     return new Promise(resolve => {
  8.         console.log('traffic-light ', color);
  9.         sleep(duration).then(resolve);
  10.     })
  11. }
  12. function main() {
  13.     return new Promise(resolve => {
  14.         changeColor(2000, 'red').then(() => {
  15.             changeColor(1000, 'yellow').then(() => {
  16.                 changeColor(3000, 'green').then(() => {
  17.                     main();
  18.                 })
  19.             })
  20.         })
  21.     })
  22. }
  23. main();


async await 实现

使用async await就可以避免Promise的一连串.then.then.then,也不再需要递归,使用while就可以实现循环。

  1. function sleep(duration) {
  2.     return new Promise(resolve => {
  3.         setTimeout(resolve, duration);
  4.     })
  5. }
  6. async function changeColor(color, duration) {
  7.     console.log('traffic-light ', color);
  8.     await sleep(duration);
  9. }
  10. async function main() {
  11.     while (true) {
  12.         await changeColor('red', 2000);
  13.         await changeColor('yellow', 1000);
  14.         await changeColor('green', 3000);
  15.     }
  16. }
  17. main();


本文网址:https://www.zztuku.com/detail-10038.html
站长图库 - Javascript怎么实现红绿灯
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐