【重學前端】紅綠燈實現

實現一個紅綠燈,把一個圓形 div 按照綠色 3 秒,黃色 1 秒,紅色 2 秒循環改變背景色。html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>紅綠燈</title>
    <style>
        .traffic-light {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            overflow: hidden;
            border: 1px solid #f1f1f1;
        }
    </style>
</head>
<body>
    <div class="traffic-light"></div>
    <script>
        function keepColor(duration) {
            return new Promise((resolve, reject) => {
                setTimeout(resolve, duration);
            });
        }
        async function changeColor (color, duration) {
            document.getElementsByClassName('traffic-light')[0].style.background = color;
            await keepColor(duration);
        }
        async function run() {
            while (1) {
                await changeColor('green', 3000); // await 要嵌套,最裏層有外層也許有
                await changeColor('yellow', 1000);
                await changeColor('red', 2000);
            }
        }
        run();
    </script>
</body>
</html>
相關文章
相關標籤/搜索