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

相关推荐
林恒smileZAZ19 小时前
Vue<前端页面版本检测>
前端·javascript·vue.js
码事漫谈1 天前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀1 天前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
014-code1 天前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024061 天前
组合模式(Composite Pattern)
开发语言
我是Superman丶1 天前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭1 天前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
游乐码1 天前
c#泛型约束
开发语言·c#
Dontla1 天前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen1 天前
python rest请求、requests
开发语言·python