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

相关推荐
吃我一窝jio7 小时前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw8 小时前
C++ union 的一种妙用法
开发语言·c++
starzy199010 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
IT_陈寒10 小时前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue11 小时前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技11 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌11 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端
再吃一根胡萝卜11 小时前
DSH 插件数据链路:Host 管数据,Client 只管画
前端
feixing_fx12 小时前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
布莱克60512 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环