<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.container {
display: flex;
}
.light {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="light"></div>
</div>
<script>
let light = document.querySelectorAll('.light')
let status = [
{ color: 'red', delay: 2000 },
{ color: 'yellow', delay: 1000 },
{ color: 'green', delay: 3000 }
]
function getInterval() {
let index = 1
let diff
return function interval(delay) {
let startTime = +new Date().getTime()
setTimeout(() => {
let endTime = new Date().getTime()
// 实际 - 理论 = 该减去的时间差
diff = endTime - startTime - delay
console.log('diff', diff)
light[0].style.backgroundColor = status[index].color
interval(status[index].delay - diff)
index++
index === 3 ? (index = 0) : ''
}, delay)
}
}
getInterval()(status[0].delay)
</script>
</body>
</html>
主要功能:红灯2秒后转黄灯,黄灯1秒后转绿灯
1.用时间补偿法纠正定时器
2.用闭包避免污染全局变量