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

所属分类: 网络编程 / JavaScript 阅读数: 984
收藏 0 赞 0 分享

要求

  • 使用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(){
  'use strict'      //严格模式
  console.log("绿灯"+new Date().getSeconds()) //绿灯执行三秒 
  traffic.className = 'green';
  green()
  .then(function(){
   console.log("黄灯"+new Date().getSeconds()) //黄灯执行四秒
   traffic.className = 'yellow';
   return yellow();
  })
  .then(function(){
   console.log("红灯"+new Date().getSeconds()) //红灯执行五秒
   traffic.className = 'red';
   return red();
  }).then(function(){
   restart()
  })
  })();

Demo 请 点击这里!

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

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

'use strict'; 
 
function async(value) { 
  return new Promise(function(resolve, reject) { 
    var ms = Math.round(Math.random() * 1000); 
    setTimeout(function() { 
      console.log('waiting ' + ms + 'ms'); 
      // 等待ms毫秒 
      resolve(value + ms); 
    }, ms); 
  }); 
} 
// 每次执行随机等待n毫秒,结果统计总毫秒数 
async(0) 
.then(async) 
.then(async) 
.then(async) 
.then(async) 
.then(function(value) { 
  console.log('------total wait:' + value + 'ms'); 
}); 
//////////////////////////////////////////////////////////// 
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('------' + value); 
}); 
///////////////////////////////////////////////////////////////// 
function say() { 
  var value = 'what'; 
  return Promise.resolve(value); 
} 
say().then(function(value) { 
  value = value + ' are'; 
  return Promise.resolve(value); 
}).then(function(value) { 
  value = value + ' you'; 
  return Promise.resolve(value); 
}).then(function(value) { 
  value = value + ' doing'; 
  return Promise.resolve(value); 
  //return Promise.reject('error, exit'); // 中途退出 
}).then(function(value) { 
  value = value + ' now!'; 
  return Promise.resolve(value); 
}).then(function(value) { 
  console.log('------' + value); 
}).catch(function(error) { 
  console.log('------' + 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="https://zhanzhang360.qulang.net/imgupload/007177/jquery.js"></script> 
</head> 
<body> 
  <div class="ball ball1"></div> 
  <div class="ball ball2"></div> 
  <div class="ball ball3"></div> 
  <script type="text/javascript"> 
    function moving(ball, pos) { 
      return new Promise(function(resolve, reject) { 
        var marginLeft = parseInt(ball.css('margin-left')); 
        if (marginLeft != pos) { 
          var timerId = setInterval(function() { 
            marginLeft = marginLeft + 1; 
            ball.css('margin-left', marginLeft); 
            if (marginLeft == pos) { 
              clearInterval(timerId); 
              resolve(); 
            } 
          }, 20); 
        } else { 
          resolve(); 
        } 
      }); 
    } 
    moving($('.ball1'), 100).then(function() { 
      return moving($('.ball2'), 150); 
    }).then(function() { 
      return moving($('.ball3'), 200); 
    }); 
  </script> 
</body> 
</html> 

以上所述是小编给大家介绍的JS 中使用Promise 实现红绿灯实例代码(demo),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

更多精彩内容其他人还在看

BootStrap数据表格实例代码

本文通过实例代码给大家分享了BootStrap数据表格的相关知识,感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

基于vue的短信验证码倒计时demo

这篇文章主要介绍了基于vue的短信验证码倒计时demo,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解React Native开源时间日期选择器组件(react-native-datetime)

本篇文章主要介绍了详解React Native开源时间日期选择器组件(react-native-datetime),具有一定的参考价值,有兴趣的可以了解一下
收藏 0 赞 0 分享

JS库particles.js创建超炫背景粒子插件(附源码下载)

particles.js用于创建粒子的轻量级 JavaScript 库。使用方法非常简单,代码也很容易实现,下面通过本文给大家分享JS库particles.js创建超炫背景粒子插件附源码下载,需要的朋友参考下吧
收藏 0 赞 0 分享

JS库之Waypoints的用法详解

waypoints的功能非常强大,一款用于捕获各种滚动事件的插件,下面跟随脚本之家小编一起学习JS库之Waypoints的用法吧
收藏 0 赞 0 分享

强大的JavaScript响应式图表Chartist.js的使用

本篇文章主要介绍了强大的JavaScript响应式图表Chartist.js的使用,具有一定的参考价值,有兴趣的可以了解一下
收藏 0 赞 0 分享

详解wow.js中各种特效对应的类名

本篇文章主要介绍了wow.js中各种特效对应的类名 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

JS库之Highlight.js的用法详解

highlight.js是一款轻量级的Web代码语法高亮库。下面通过实例代码给大家分享JS库之Highlight.js的用法详解,感兴趣的朋友跟随脚本之家小编一起学习吧
收藏 0 赞 0 分享

详解动画插件wow.js的使用方法

本篇文章主要介绍了动画插件wow.js的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

JS库 Highlightjs 添加代码行号的实现代码

Highlightjs是一款优秀的代码高亮Js组件,可以很方便地对各种语言编写的代码添加语法高亮样式。本文重点给大家介绍Highlightjs 添加代码行号的实现代码,需要的朋友参考下吧
收藏 0 赞 0 分享
查看更多