promise 实现红绿灯

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>红绿灯</title>
</head>
<style>
ul {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

  /*画3个圆代表红绿灯*/

  ul >li {
      width: 40px;
      height: 40px;
      border-radius:50%;
      opacity: 0.2;
      display: inline-block;
  }

  /*执行时改变透明度*/

  ul.red >#red, 
  ul.green >#green,
  ul.yellow >#yellow{
      opacity: 1.0;
  }

  /*红绿灯的三个颜色*/

  #red {background: red;}

  #yellow {background: yellow;}

  #green {background: green;}
</style>
<body>
  <ul id="main" class="">
    <li id="green"></li>
    <li id="yellow"></li>
    <li id="red"></li>
  </ul>
</body>
<script>
  function timeOut(timer){
      return function(){ 
          return new Promise(function(resolve,reject){
            setTimeout(resolve,timer) 
          })        
        }
      }
    var green = timeOut(5000);
    var yellow = timeOut(2000);
    var red = timeOut(3000);
    var main = document.getElementById("main");

    (function restart(){
      'use strict'                     //严格模式
      console.log("绿灯"+new Date().getSeconds())  //绿灯执行5秒 
      main.className = 'green';

      green()
      .then(function(){
          console.log("黄灯"+new Date().getSeconds())  //黄灯执行2秒
          main.className = 'yellow';
          return yellow();
        })
      .then(function(){
          console.log("红灯"+new Date().getSeconds())   //红灯执行3秒
          main.className = 'red';
          return red();
        }).then(function(){
          restart()
        })
      })();
</script>
</html>

 

posted @ 2019-05-12 12:58  不知不觉、  阅读(754)  评论(0编辑  收藏  举报