Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - What's going wrong with my timed Traffic Lights program?

I don't know why as it seems to be all correct and there are no errors in console. It always starts on green.png and stays there? I'm trying to make a timed traffic lights sequence that can start as soon as the page is loaded without a button.

<!DOCTYPE html>
<html>
<head>
</head>
    <body>
        <h2>Traffic Lights Program</h2>
        <div class="light"><img src="Blank.png" style="width:100px;height:228px;"/></div>

        <script>
        trafficLight = "green";
        var trafficLights = ["Red.png","RedYellow.png","Yellow.png","Green.png"]
        function green() {
            document.images[0].src = trafficLights[3];
        }

        function yellow() {
            document.images[0].src = trafficLights[3];
        }

        function redYellow() {
            document.images[0].src = trafficLights[1];
        }

        function red() {
            document.images[0].src = trafficLights[0];
        }

        function yellow2() {
            document.images[0].src = trafficLights[2];
        }

        function automatic() {
            if (trafficLight = "green") {
                setTimeout(green(),500)
                var trafficLight = "yellow";
            } else if (trafficLight = "yellow") {
                setTimeout(yellow(),500)
                var trafficLight = "redYellow";
            } else if (trafficLight = "redYellow") {
                setTimeout(redYellow(),500)
                var trafficLight = "red";
            } else if (trafficLight = "red") {
                setTimeout(red(),500)
                var trafficLight = "yellow2";       
            } else {
                setTimeout(yellow2(),500)
                var trafficLight = "green";
            }   
        }

        setInterval(automatic(),1000)
    </script>
    </body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

None of your conditionals are executing the way you intended since they are set up using the assignment operator "=" rather than comparative operator "==".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...