You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现带启停按钮的交通灯定时器功能

问题原因

现有代码默认自动运行的核心原因是页面加载完成后直接调用了setInterval(timerSet,1500),无需用户操作就会自动触发定时器;同时启动按钮的事件绑定逻辑错误、缺少停止按钮的事件监听,无法实现手动控制。

修改方案

需要调整3处逻辑:

  • 删除页面加载时自动创建定时器的代码,避免进入页面就自动运行
  • 改写启动按钮的点击事件:每次点击前先清空已存在的定时器(防止多次点击启动生成多个定时器导致切换速度异常),再创建新的循环定时器
  • 新增停止按钮的点击事件:点击时清空正在运行的定时器,交通灯就会停在当前状态

修改后完整代码

<button id="btn1">start</button>
<button id="btn2">stop</button>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

<script>
const btn1=document.getElementById("btn1");
const btn2=document.getElementById("btn2");
const div1=document.getElementById("div1");
const div2=document.getElementById("div2");
const div3=document.getElementById("div3");

let timer = null;
// 启动按钮绑定事件
btn1.addEventListener("click", () => {
    // 清空已有定时器,避免重复启动
    if(timer) clearInterval(timer);
    // 启动新的循环定时器
    timer = setInterval(timerSet,1500);
})
// 停止按钮绑定事件
btn2.addEventListener("click", () => {
    if(timer) {
        clearInterval(timer);
        timer = null;
    }
})

function timerSet(){
    if(div1.style.backgroundColor=="red"){
        div2.style.backgroundColor="yellow";
        div1.style.backgroundColor="black";
        div3.style.backgroundColor="black";
    }
    else if(div2.style.backgroundColor=="yellow"){
        div3.style.backgroundColor="green";
        div2.style.backgroundColor="black";
        div1.style.backgroundColor="black";
    }
    else if (div3.style.backgroundColor=="green"){
        div1.style.backgroundColor="red";
        div3.style.backgroundColor="black";
    }
}

Kreis(div1,20,"red");
Kreis(div2,20,"black");
Kreis(div3,20,"black");

function Kreis(element,radius,farbe){
    element.style.backgroundColor=farbe;
    element.style.width=2*radius+"px";
    element.style.height=2*radius+"px";
    element.style.borderRadius=2*radius+"px";
}
</script>

内容的提问来源于stack exchange,提问作者black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:18:00