ArthurWangCN / notepad

reading notepad
0 stars 2 forks source link

async / await #11

Open ArthurWangCN opened 2 years ago

ArthurWangCN commented 2 years ago

defination

ArthurWangCN commented 2 years ago

usage

ArthurWangCN commented 2 years ago

小练习:我们现在要实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色

function sleep(duration){
    return new Promise(function(resolve){
        setTimeout(resolve, duration);
    })
}
async function changeColor(duration,color){
    document.getElementById("traffic-light").style.background = color;
    await sleep(duration);

}
async function main(){
    while(true){
        await changeColor(3000,"green");
        await changeColor(1000, "yellow");
        await changeColor(2000, "red");
    }
}
main()