JS 中使用Promise 实现红绿灯实例代码(demo)
要求
- 使用promise实现红绿灯颜色的跳转
- 绿灯执行三秒后
- 黄灯执行四秒后
- 红灯执行五秒
html实现如下:
定义一个空类,之后再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代码如下:
functiontimeout(timer){
returnfunction(){
returnnewPromise(function(resolve,reject){
setTimeout(resolve,timer)
})
}
}
vargreen=timeout(3000);
varyellow=timeout(4000);
varred=timeout(5000);
vartraffic=document.getElementById("traffic");
(functionrestart(){
'usestrict'//严格模式
console.log("绿灯"+newDate().getSeconds())//绿灯执行三秒
traffic.className='green';
green()
.then(function(){
console.log("黄灯"+newDate().getSeconds())//黄灯执行四秒
traffic.className='yellow';
returnyellow();
})
.then(function(){
console.log("红灯"+newDate().getSeconds())//红灯执行五秒
traffic.className='red';
returnred();
}).then(function(){
restart()
})
})();
Demo请点击这里!
ps:下面看一个Promise用法例子
注意:要想then方法能链式的执行下去,必须返回Promise对象!!!
'usestrict';
functionasync(value){
returnnewPromise(function(resolve,reject){
varms=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('------totalwait:'+value+'ms');
});
////////////////////////////////////////////////////////////
functionasync1(value){
returnnewPromise(function(resolve,reject){
resolve(value+1);
});
}
functionasync2(value){
//returnnewPromise(function(resolve,reject){
//resolve(value+2);
//});
//等价与上面写法
returnPromise.resolve(value+2);
}
functionasync3(value){
returnnewPromise(function(resolve,reject){
resolve(value+3);
});
}
async1(100).then(async2).then(async3).then(function(value){
console.log('------'+value);
});
/////////////////////////////////////////////////////////////////
functionsay(){
varvalue='what';
returnPromise.resolve(value);
}
say().then(function(value){
value=value+'are';
returnPromise.resolve(value);
}).then(function(value){
value=value+'you';
returnPromise.resolve(value);
}).then(function(value){
value=value+'doing';
returnPromise.resolve(value);
//returnPromise.reject('error,exit');//中途退出
}).then(function(value){
value=value+'now!';
returnPromise.resolve(value);
}).then(function(value){
console.log('------'+value);
}).catch(function(error){
console.log('------'+error);
});
Ballmove
.ball{
width:40px;
height:40px;
border-radius:20px;
margin-left:10px;
}
.ball1{
background:#ff0000;
}
.ball2{
background:#00ff00;
}
.ball3{
background:#0000ff;
}