题目说的是实现红灯10s 黄灯3秒 绿灯5秒
还有当前时间到国庆之间的计算与显示
效果如下
用Promise
和async await
来实现这个功能
思路:
封装一个时间处理函数,在promise
里面用永久定时器调用使它实时获取最新时间进行计算,以及对红绿灯时间的一个递减操作,然后定时器时间到了就清除上面的永久定时器并进行样式排他的操作 再使用闭包 以此循环
样式:
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
display: flex;
width: 200px;
border: 1px solid black;
}
.container span {
border: 1px solid;
width: 50px;
height: 50px;
border-radius: 50%;
}
.container .time {
text-align: center;
line-height: 52px;
width: 50px;
height: 52px;
background-color: #adadad;
}
.render2Time {
font-size: 20px;
margin-top: 20px;
}
.red1 {
background-color: rgb(243, 98, 98);
}
.yellow1 {
background-color: rgb(218, 241, 113);
}
.green1 {
background-color: rgb(130, 245, 126);
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
</style>
布局以及JS
<div class="container">
<span id="red" class="red1"></span>
<span id="yellow" class="yellow1"></span>
<span id="green" class="green1"></span>
<div class="time"></div>
</div>
<div class="render2Time">距离国庆还有...</div>
<script>
function light(color, delary) {
let timer = null
timer = setInterval(() => {
redenerTime()
if (document.querySelector('.time').innerHTML > 0) {
document.querySelector('.time').innerHTML -= 1
}
}, 1000)
document.querySelector('.time').innerHTML = (delary / 1000)
document.querySelector(`#${color}`).classList.add(`${color}`)
// love(delary)
return new Promise((resolve, reject) => {
setTimeout(() => {
document.querySelector(`#${color}`).classList.remove(`${color}`)
resolve()
clearInterval(timer)
}, delary)
})
}
function redenerTime() {
// 国庆时间格式
let today = new Date()
let endDay = new Date('2022/10/1')
let result = (endDay.getTime() - today.getTime()) / 1000
let day = parseInt(result / (24 * 60 * 60))
let hour = parseInt((result - day * 24 * 60 * 60) / (60 * 60))
let minite = parseInt(
(result - day * 24 * 60 * 60 - hour * 60 * 60) / 60
)
let sec = parseInt(
result - day * 24 * 60 * 60 - hour * 60 * 60 - minite * 60
)
document.querySelector('.render2Time').innerHTML =
'距离国庆放假还有:' +
day +
'天' +
hour +
'小时' +
minite +
'分钟' +
sec +
'秒'
}
async function P() {
await redenerTime()
await light('red', 10000)
await light('yellow', 3000)
await light('green', 5000)
P()
}
P()
</script>
最新回复