使用promise 实现红绿灯颜色的跳转
红灯执行1秒
绿灯执行2秒后
黄灯执行3秒后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
div {
height: 100px;
width: 100px;
border: 1px solid #000;
background: red;
border-radius: 50px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<script>
function light(color, timer) {
return new Promise((resolve, reject) => {
setTimeout(function () {
var div = document.getElementsByTagName("div")[0]
div.style.backgroundColor = color
resolve(color)
}, timer)
})
}
(function restart() {
'use strict'
light('red', 1000).then((data) => {
console.log(data,new Date().getSeconds());
return light('green', 2000)
}).then((data) => {
console.log(data,new Date().getSeconds());
return light('yellow', 3000)
}).then((data)=>{
console.log(data,new Date().getSeconds());
return restart()
})
})();
</script>