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

相关推荐
蔗理苦2 分钟前
2025-09-05 CSS3——盒子模型
前端·css·css3
中国胖子风清扬11 分钟前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
我就是全世界15 分钟前
【存储选型终极指南】RustFS vs MinIO:5大维度深度对决,95%技术团队的选择秘密!
开发语言·分布式·rust·存储
yudiandian201434 分钟前
【QT 5.12.12 打包-Windows 平台下】
开发语言·qt
要记得喝水35 分钟前
C#某公司面试题(含题目和解析)--1
开发语言·windows·面试·c#·.net
二川bro44 分钟前
第25节:VR基础与WebXR API入门
前端·3d·vr·threejs
金融数据出海1 小时前
黄金金融期货数据API对接技术文档
开发语言·金融·github
上单带刀不带妹1 小时前
Node.js 的模块化规范是什么?CommonJS 和 ES6 模块有什么区别?
前端·node.js·es6·模块化