最近看了winter老师《重学前端》里的“Promise里的代码为什么比setTimeout先执行?”一章,以下是做的红绿灯练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>红绿灯</title>
    <style>
        #light {
            width:50px;
            height: 50px;
            border-radius:50%;
            border: solid 1px #333;
        }
    </style>
</head>
<body>
    <div id="light"></div>
</body>
<script>
    function sleep(duration) {
        return new Promise(function (resolve, reject) {
            setTimeout(resolve, duration)
        })
    }
    const light = document.getElementById('light')
    async function changeBgColor (duration, color) {
        light.style.background = color
        await sleep(duration)
    }
    async function main() {
        while(true) {
        await changeBgColor(3000, 'green')
        await changeBgColor(1000, 'yellow')
        await changeBgColor(2000, 'red')
        }
    }
    main()
</script>
</html>