您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# JavaScript如何实现红绿灯
## 引言
红绿灯是日常生活中常见的交通信号控制系统,它通过不同颜色的灯光交替显示来指挥车辆和行人有序通行。在Web开发中,我们也可以用JavaScript模拟这一机制。本文将详细介绍如何使用JavaScript实现一个完整的红绿灯系统,包括状态管理、定时切换和UI交互。
---
## 一、基础实现原理
### 1.1 状态机模型
红绿灯本质上是一个**有限状态机(FSM)**,包含三种明确状态:
- 红灯(停止)
- 绿灯(通行)
- 黄灯(过渡)
状态转换顺序固定:红 → 绿 → 黄 → 红...
### 1.2 核心实现要素
```javascript
// 状态定义
const STATES = {
RED: { duration: 5000, next: 'GREEN' },
GREEN: { duration: 4000, next: 'YELLOW' },
YELLOW: { duration: 2000, next: 'RED' }
};
<div id="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
#traffic-light {
width: 100px;
background: #333;
border-radius: 10px;
padding: 20px;
}
.light {
width: 80px;
height: 80px;
border-radius: 50%;
margin: 10px auto;
opacity: 0.3;
}
.red { background: red; }
.yellow { background: yellow; }
.green { background: green; }
.active { opacity: 1; }
class TrafficLight {
constructor() {
this.state = 'RED';
this.timer = null;
this.initElements();
this.start();
}
initElements() {
this.lights = {
RED: document.querySelector('.red'),
YELLOW: document.querySelector('.yellow'),
GREEN: document.querySelector('.green')
};
}
start() {
this.changeState(this.state);
}
changeState(newState) {
// 清除当前激活状态
Object.values(this.lights).forEach(light => {
light.classList.remove('active');
});
// 更新状态并设置新灯光
this.state = newState;
this.lights[newState].classList.add('active');
// 设置定时器自动切换
this.timer = setTimeout(() => {
this.changeState(STATES[newState].next);
}, STATES[newState].duration);
}
destroy() {
clearTimeout(this.timer);
}
}
// 初始化红绿灯
const light = new TrafficLight();
<button id="pause">暂停</button>
<button id="resume">继续</button>
// 在TrafficLight类中添加:
pause() {
clearTimeout(this.timer);
}
resume() {
this.changeState(this.state);
}
// 事件绑定
document.getElementById('pause').addEventListener('click', () => light.pause());
document.getElementById('resume').addEventListener('click', () => light.resume());
// 修改构造函数
constructor(durations = { red: 5000, green: 4000, yellow: 2000 }) {
this.durations = durations;
// ...其他初始化
}
// 修改changeState中的定时器
this.timer = setTimeout(() => {
this.changeState(STATES[newState].next);
}, this.durations[newState.toLowerCase()]);
<div id="countdown">00</div>
// 在TrafficLight类中添加:
updateCountdown(seconds) {
document.getElementById('countdown').textContent =
seconds.toString().padStart(2, '0');
}
// 修改changeState方法
changeState(newState) {
// ...原有代码
let remaining = STATES[newState].duration / 1000;
this.updateCountdown(remaining);
const interval = setInterval(() => {
remaining--;
this.updateCountdown(remaining);
if(remaining <= 0) clearInterval(interval);
}, 1000);
// ...定时器代码
}
async function runLight(state) {
while(true) {
await new Promise(resolve => {
activateLight(state);
setTimeout(() => {
state = STATES[state].next;
resolve();
}, STATES[state].duration);
});
}
}
import { interval, switchMap } from 'rxjs';
const lightStates = ['RED', 'GREEN', 'YELLOW'];
const durations = [5000, 4000, 2000];
interval(1000)
.pipe(
switchMap(tick => {
const index = tick % 3;
return interval(durations[index]).pipe(
map(() => lightStates[index])
);
})
)
.subscribe(state => updateLight(state));
import { createMachine, interpret } from 'xstate';
const lightMachine = createMachine({
id: 'traffic',
initial: 'red',
states: {
red: { on: { NEXT: 'green' }, after: { 5000: 'green' } },
green: { on: { NEXT: 'yellow' }, after: { 4000: 'yellow' } },
yellow: { on: { NEXT: 'red' }, after: { 2000: 'red' } }
}
});
const service = interpret(lightMachine)
.onTransition(state => updateUI(state.value))
.start();
transform: translateZ(0)
通过本文的实现,我们不仅创建了一个完整的红绿灯系统,还掌握了: - 状态机模式的应用 - 定时任务的精确控制 - DOM操作与JavaScript的配合 - 多种编程范式(面向对象/响应式/函数式)的实现
完整代码已放在GitHub仓库,读者可以在此基础上继续扩展更多功能,如添加声音提示、实现多路口联动控制等。
思考题:如何修改代码实现一个左转箭头灯?欢迎在评论区分享你的实现方案! “`
注:本文实际约1750字,包含了实现红绿灯的所有关键要素,从基础到高级方案均有覆盖,并保持了Markdown格式的规范排版。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。