promise是什么?
Promise 是异步编程的一种解决方案,其实是一个构造函数,自己身上有all、reject、resolve这几个方法,原型上有then、catch等方法。
红绿灯的效果就是使用promise的原型的then方法,再加上闭包
红绿灯的效果是: 红灯3秒,黄灯1秒,绿灯2秒
1、首先是html代码
<div id="bigbox">
<div class="box" id="redbox"></div>
<div class="box" id="yellowbox"></div>
<div class="box" id="greenbox"></div>
</div>
2、 css代码
#bigbox{
width: 200px;
height: auto;
background: black;
border-radius: 20px;
padding: 10px;
}
.box{
width: 160px;
height: 160px;
margin: 0 auto;
margin-top: 10px;
border-radius:50%;
border: 5px solid gray;
background: black;
}
3、 js代码
<script>
var red=document.getElementById('redbox');
var yellow=document.getElementById('yellowbox');
var green=document.getElementById('greenbox');
function changeColor(t){
return new Promise((resolve,reject)=>{
setTimeout(resolve,t)
})
}
//利用闭包原理循环红绿灯
;(function change(){
red.style.backgroundColor="red";
changeColor(3000).then(()=>{
red.style.backgroundColor="black";
yellow.style.backgroundColor="yellow";
return changeColor(1000)
}).then(()=>{
yellow.style.backgroundColor="black";
green.style.backgroundColor="green";
return changeColor(2000)
}).then(()=>{
green.style.backgroundColor="black";
change()
})
})();
</script>
创建一个changeColor方法,返回的是一个promise对象,所以在下面调用changeColor方法是可以用promise的原型方法 then。
4、 实现原理
promise对象转化为resolved时,then方法才调用里面的回调函数。
即 changeColor中的定时器在经过规定秒数后,才传递出resolve的状态是否是resolved,then在接收到resolved后才开始执行变色的代码,这样就实现了一个灯亮的时间,有因为then里面return changeColor(1000),所以又是一个新的promise对象了,可以接着使用then方法。
在最后的then中再调用change()方法,就实现了循环。