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

相关推荐
沉迷学习日益消瘦几秒前
8 UI 组件库与设计系统:Token 驱动 + 暗色模式 + 4 种主题色
前端
熬夜苦读学习7 分钟前
QT_信号和槽
开发语言·qt
代码雕刻家10 分钟前
编程语法细节
java·c语言·开发语言
j7~11 分钟前
【C++】C++ 继承全解析:从基本语法到菱形继承的底层原理
开发语言·c++·继承·组合·虚继承·#暑假·七月创作之星博客挑战赛
数行拙笔14 分钟前
C++客户端---String类型
开发语言·c++·bootstrap
CodeSheep16 分钟前
有这4个迹象,你就该离职了!
前端·后端·程序员
用户0595401744616 分钟前
把大模型记忆回归测试从手工检查换成 Playwright+VCR,误判率从 40% 降到 0
前端·css
倾颜17 分钟前
pnpm 负责依赖,Turbo 负责任务:一次小型 Monorepo 治理的边界取舍
前端·next.js
程序员爱钓鱼17 分钟前
Rust 元组 Tuple 详解:组合不同类型的数据
前端·后端·rust
影寂ldy21 分钟前
C# Task 进阶:WaitAll / WaitAny / WhenAll / WhenAny
开发语言·c#