js手写红绿灯(带优化版)

复制代码
<!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.用闭包避免污染全局变量

相关推荐
前端一课几秒前
【vue高频面试题】第3题:Vue 3 中的 computed 是什么?和 watch 有什么区别?什么时候用哪一个?
前端·面试
vi121234 分钟前
ENVI 地形量化与植被指数反演
开发语言·python
Json____5 分钟前
vue2-数码购物商城-前端静态网站
前端·vue·数码商城
u***28477 分钟前
golang debug调试
开发语言·后端·golang
@大迁世界9 分钟前
03.CSS嵌套 (Nesting)
前端·css
DevUI团队11 分钟前
解锁前端高阶调试:浏览器/IDE/Git技巧分享
前端·javascript·html
前端一课15 分钟前
【vue高频面试题】第一题:Vue 3 相比 Vue 2,有哪些重大变化?
前端·面试
lly20240615 分钟前
Bootstrap 滚动监听
开发语言
前端一课17 分钟前
【vue高频面试题】第2题:Vue 3 中 ref 和 reactive 的区别是什么?什么时候用哪一个?
前端·面试
星释17 分钟前
Rust 练习册 99:让数字开口说话
开发语言·后端·rust