一个promise红绿灯的例子,有助于自己简单了解promise的运行机制,虽然说在前面又简单介绍promise,但是感觉没有一个直观的例子来的强烈!
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;
}
html
<ul id="traffic" class="">
<li id="green"></li>
<li id="yellow"></li>
<li id="red"></li>
</ul>
javascript
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' //严格模式
traffic.className = 'green';
green()
.then(function() {
traffic.className = 'yellow';
return yellow();
})
.then(function() {
traffic.className = 'red';
return red();
}).then(function() {
restart()
})
})();