利用promise实现一个红绿灯轮训的函数

55 阅读1分钟

通过setTimout和await来控制时间及循环,设置不同的响应时间来保证执行。

有待加强,如果要求每个setTimout都是1000ms该如何处理

async function timer(color,delay){
    return new Promise((res,rej)=>{
        console.log(color)
        setTimeout(() => {
            res()
        }, delay);
    })
}
async function light(){
    await timer('green',1000)
    await timer('yellow',2000)
    await timer('red',3000)
}

async function light(){
    await timer('green',1000)
    await timer('yellow',2000)
    await timer('red',3000)
    await light()
}
light()