首页 > web前端 > js教程 > 正文

JS 中使用Promise 实现红绿灯实例代码(demo)

韦小宝
发布: 2018-01-11 10:16:27
原创
2510 人浏览过

本文通过实例代码给大家介绍了JS 中使用Promise 实现红绿灯效果,在文中给大家介绍了一个promise用法例子,不了解js中如何使用Promise的朋友可以参考下本篇文章

要求

  • 使用promise 实现红绿灯颜色的跳转

  • 绿灯执行三秒后

  • 黄灯执行四秒后

  • 红灯执行五秒

html 实现如下:

<ul id="traffic" class="">
 <li id="green"></li>
 <li id="yellow"></li>
 <li id="red"></li>
</ul>
登录后复制

定义一个空类,之后再js中操作对应的类名即可实现相关的效果。

CSS实现如下:

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;}
登录后复制

javascript原理:

promise函数为一个异步操作函数,在函数运行结束时可以使用then()方法。我们再在promise函数内部设置延迟执行即可实现。

js 代码如下:

function timeout(timer){
  return function(){ 
   return new Promise(function(resolve,reject){
   setTimeout(resolve,timer) 
   })  
  }
  }
 var green = timeout(3000);
 var yellow = timeout(4000);
 var red = timeout(5000);
 var traffic = document.getElementById("traffic");
 (function restart(){
  &#39;use strict&#39;      //严格模式
  console.log("绿灯"+new Date().getSeconds()) //绿灯执行三秒 
  traffic.className = &#39;green&#39;;
  green()
  .then(function(){
   console.log("黄灯"+new Date().getSeconds()) //黄灯执行四秒
   traffic.className = &#39;yellow&#39;;
   return yellow();
  })
  .then(function(){
   console.log("红灯"+new Date().getSeconds()) //红灯执行五秒
   traffic.className = &#39;red&#39;;
   return red();
  }).then(function(){
   restart()
  })
  })();
登录后复制

ps:下面看一个Promise用法例子

注意:要想then方法能链式的执行下去,必须返回Promise对象!!!

&#39;use strict&#39;; 
 
function async(value) { 
  return new Promise(function(resolve, reject) { 
    var ms = Math.round(Math.random() * 1000); 
    setTimeout(function() { 
      console.log(&#39;waiting &#39; + ms + &#39;ms&#39;); 
      // 等待ms毫秒 
      resolve(value + ms); 
    }, ms); 
  }); 
} 
// 每次执行随机等待n毫秒,结果统计总毫秒数 
async(0) 
.then(async) 
.then(async) 
.then(async) 
.then(async) 
.then(function(value) { 
  console.log(&#39;------total wait:&#39; + value + &#39;ms&#39;); 
}); 
//////////////////////////////////////////////////////////// 
function async1(value) { 
  return new Promise(function(resolve, reject) { 
    resolve(value + 1); 
  }); 
} 
function async2(value) { 
  // return new Promise(function(resolve, reject) { 
  //   resolve(value + 2); 
  // }); 
  // 等价与上面写法 
  return Promise.resolve(value + 2); 
} 
function async3(value) { 
  return new Promise(function(resolve, reject) { 
    resolve(value + 3); 
  }); 
} 
async1(100).then(async2).then(async3).then(function(value) { 
  console.log(&#39;------&#39; + value); 
}); 
///////////////////////////////////////////////////////////////// 
function say() { 
  var value = &#39;what&#39;; 
  return Promise.resolve(value); 
} 
say().then(function(value) { 
  value = value + &#39; are&#39;; 
  return Promise.resolve(value); 
}).then(function(value) { 
  value = value + &#39; you&#39;; 
  return Promise.resolve(value); 
}).then(function(value) { 
  value = value + &#39; doing&#39;; 
  return Promise.resolve(value); 
  //return Promise.reject(&#39;error, exit&#39;); // 中途退出 
}).then(function(value) { 
  value = value + &#39; now!&#39;; 
  return Promise.resolve(value); 
}).then(function(value) { 
  console.log(&#39;------&#39; + value); 
}).catch(function(error) { 
  console.log(&#39;------&#39; + error); 
}); 
<html> 
<head> 
  <title>Ball move</title> 
  <style type="text/css"> 
    .ball { 
      width: 40px; 
      height: 40px; 
      border-radius: 20px; 
      margin-left: 10px; 
    } 
    .ball1 { 
      background: #ff0000; 
    } 
    .ball2 { 
      background: #00ff00; 
    } 
    .ball3 { 
      background: #0000ff; 
    } 
  </style> 
  <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> 
</head> 
<body> 
  <p class="ball ball1"></p> 
  <p class="ball ball2"></p> 
  <p class="ball ball3"></p> 
  <script type="text/javascript"> 
    function moving(ball, pos) { 
      return new Promise(function(resolve, reject) { 
        var marginLeft = parseInt(ball.css(&#39;margin-left&#39;)); 
        if (marginLeft != pos) { 
          var timerId = setInterval(function() { 
            marginLeft = marginLeft + 1; 
            ball.css(&#39;margin-left&#39;, marginLeft); 
            if (marginLeft == pos) { 
              clearInterval(timerId); 
              resolve(); 
            } 
          }, 20); 
        } else { 
          resolve(); 
        } 
      }); 
    } 
    moving($(&#39;.ball1&#39;), 100).then(function() { 
      return moving($(&#39;.ball2&#39;), 150); 
    }).then(function() { 
      return moving($(&#39;.ball3&#39;), 200); 
    }); 
  </script> 
</body> 
</html>
登录后复制

以上所述是小编给大家介绍的JS 中使用Promise 实现红绿灯实例代码(demo),希望对大家有所帮助!!

相关推荐:

jQuery之Promise的具体使用方法

你实现一个完整的 Promise的方法

关于promise对象的简单用法

以上是JS 中使用Promise 实现红绿灯实例代码(demo)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!