<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
div {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid black;
text-align: center;
line-height: 50px;
font-size: 30px;
font-weight: bold;
color: white;
}
#redLight {
background-color: white;
}
#greenLight {
background-color: white;
}
#yellowLight {
background-color: white;
}
</style>
</head>
<body>
<div id="redLight"></div><br>
<div id="greenLight"></div><br>
<div id="orangeLight"></div><br>
</body>
</html>
<script>
function int(num,id,color){
document.getElementById(id).style.backgroundColor=color;
document.getElementById(id).innerHTML=num;
return new Promise(function(resolve,reject){
let time=setInterval(function(){
num--;
if(num<=0){
num=0;
clearInterval(time);
time=undefined;
document.getElementById(id).style.backgroundColor="white";
resolve();
}
document.getElementById(id).innerHTML=num;
},1000)
})
}
function ints(){
int(3,"redLight","red")
.then(function(){
return int(3,"greenLight","green");
})
.then(function(){
return int(3,"orangeLight","orange");
})
.then(ints);
}
ints();
</script>
// 红灯闪烁的代码
function redShan() {
let num = 3;
document.getElementById("redLight").style.backgroundColor = "red";
document.getElementById("redLight").innerHTML = num;
return new Promise(function (resolve, reject) {
let myTimer = setInterval(function () {
num--;
if (num <= 0) {//良性冗余
num = 0;
clearInterval(myTimer);
myTimer = undefined;
document.getElementById("redLight").style.backgroundColor = "white";
resolve();
}
document.getElementById("redLight").innerHTML = num;
}, 1000)
})
}
//黄灯闪烁代码
//红灯闪烁代码
//...只是改变了获取的dom,以及一些style样式,造成代码冗余,所以上面的代码是对其的封装