声明一个函数light,接收时间、颜色、当前标签三个参数,函数中获取当前标签并改变其背景颜色赋值,返回promise,成功执行一个延时器,延时器中执行promise成功的回调
声明另一个函数step,并执行 Promise.resolve().then方法,方法中分别获取三个灯的标签,并未当前标签背景颜色设置为白色,返回 light(时间,颜色, 当前标签);
执行 step 函数
<!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>
</head>
<body>
<div style="display: flex">
<div
style="
padding: 10px 15px;
background-color: black;
border: 1px solid #666;
border-radius: 15px;
"
>
<div
class="redbox"
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
</div>
<div
style="
padding: 10px 15px;
background-color: black;
border: 1px solid #666;
border-radius: 15px;
"
>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
class="greenbox"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
</div>
<div
style="
padding: 10px 15px;
background-color: black;
border: 1px solid #666;
border-radius: 15px;
"
>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
></div>
<div
style="
width: 100px;
height: 100px;
border: 1px solid #fff;
background: #fff;
border-radius: 50%;
"
class="yellowbox"
></div>
</div>
</div>
<script>
let light = function (timmer, color, box) {
console.log(box);
let divbox = document.querySelector("." + box);
divbox.style.backgroundColor = color;
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, timmer);
});
};
let step = function () {
Promise.resolve()
.then(function () {
let divbox = document.querySelector("." + "yellowbox");
divbox.style.backgroundColor = "#fff";
return light(3000, "red", "redbox");
})
.then(function () {
let divbox = document.querySelector("." + "redbox");
divbox.style.backgroundColor = "#fff";
return light(2000, "green", "greenbox");
})
.then(function () {
let divbox = document.querySelector("." + "greenbox");
divbox.style.backgroundColor = "#fff";
return light(1000, "yellow", "yellowbox");
})
.then(function () {
step();
});
};
step();
</script>
</body>
</html>