promise红绿灯

本文介绍了一个使用Promise实现的交通灯模拟案例。通过redFunc、greenFunc和yellowFunc函数分别控制红绿黄灯的显示,每个颜色的灯显示指定秒数后自动切换。利用Promise的then方法串联各个阶段,实现灯效的连续变化。当红灯结束后,会再次调用shine函数,形成交通灯的循环效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面这是一个用promise写的小案例 红绿灯 当成功时调用resolve(); 使用promise的then方法 接收结果

Title

function redFunc(){
$("#redLight").style.background=“orangered”;
let count=6;
$("#redLight").innerHTML=count;
return new Promise(function(resolve, reject){
let myTimer=setInterval(()=>{
count–;
$("#redLight").innerHTML=count;
if(count<=0){
count=0;
clearInterval(myTimer);
$("#redLight").innerHTML=" “;
$(”#redLight").style.background=“white”;
resolve();
}
},1000);
})
}
function greenFunc(){
$("#greenLight").style.background=“lightgreen”;
let count=4;
$("#greenLight").innerHTML=count;

return new Promise(function(resolve, reject){
    let myTimer=setInterval(()=>{
        count--;
        $("#greenLight").innerHTML=count;
        if(count<=0){
            count=0;
            clearInterval(myTimer);
            $("#greenLight").innerHMTL=" ";
            $("#greenLight").style.background="white";
            resolve();
        }

    },1000);
})

}

function yellowFunc(){
$("#yellowLight").style.background=“yellow”;
let count=2;
$("#yellowLight").innerHTML=count;

return new Promise(function(resolve, reject){
    let myTimer=setInterval(()=>{
        count--;
        if(count<=0){
            count=0;
            clearInterval(myTimer);
            $("#yellowLight").innerHTML=" ";
            $("#yellowLight").style.background="white";
            resolve();
        }
        $("#yellowLight").innerHTML=count;
    },1000);
})

}

function shine(){
redFunc().then(greenFunc).then(yellowFunc).then(shine);
}

window.οnlοad=function(){
shine();
}

function $(str){
    if(str.charAt(0)=="#"){
        return document.getElementById(str.substring(1));
    }else if(str.charAt(0)=="."){
        return document.getElementsByClassName(str.substring(1));
    }else{
        return document.getElementsByTagName(str);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值