实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色

343 阅读1分钟

直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test light color</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    #light{
        width:100px;
        height:100px;
        border-radius: 100%;
        margin:50px auto;
    }
</style>
<body>
    <div id="light"></div>
</body>
<script>
    /* 
我们现在要实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色
 */

function sleep(duration){
    return new Promise(function(resolve){
        setTimeout(resolve,duration)
    })
}

async function changeColor(duration,color){
    document.getElementById('light').style.background = color
    await sleep(duration)
}

async function main(){
//while true 无限循环
    while(true){
        await changeColor(3000,'green');
        await changeColor(2000,'yellow');
        await changeColor(1000,'red');
    }
}
main()
</script>
</html>