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

相关推荐
骁的小小站4 分钟前
Verilator 和 GTKwave联合仿真
开发语言·c++·经验分享·笔记·学习·fpga开发
林强1811 小时前
前端文件预览docx、pptx和xlsx
前端
心灵宝贝2 小时前
申威架构ky10安装php-7.2.10.rpm详细步骤(国产麒麟系统64位)
开发语言·php
lly2024062 小时前
PHP 字符串操作详解
开发语言
像是套了虚弱散4 小时前
DevEco Studio与Web联合开发:打造鸿蒙混合应用的全景指南
开发语言·前端·华为·harmonyos·鸿蒙
旭意4 小时前
C++蓝桥杯之结构体10.15
开发语言·c++
衬衫chenshan4 小时前
【CTF】强网杯2025 Web题目writeup
前端
飞翔的佩奇4 小时前
【完整源码+数据集+部署教程】【天线&水】舰船战舰检测与分类图像分割系统源码&数据集全套:改进yolo11-repvit
前端·python·yolo·计算机视觉·数据集·yolo11·舰船战舰检测与分类图像分割系统
麦麦鸡腿堡5 小时前
Java的单例设计模式-饿汉式
java·开发语言·设计模式
哆啦A梦15885 小时前
点击Top切换数据
前端·javascript·vue.js