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
Solution 1:
None of your conditionals are executing the way you intended since they are set up using the assignment operator "=" rather than comparative operator "==".
Solution 2:
I've cleaned up your code a bit:
functionautomatic() {
if (trafficLight == "green") {
setTimeout(green,500);
trafficLight = "yellow";
} elseif (trafficLight == "yellow") {
setTimeout(yellow,500);
trafficLight = "redYellow";
} elseif (trafficLight == "redYellow") {
setTimeout(redYellow,500);
trafficLight = "red";
} elseif (trafficLight == "red") {
setTimeout(red,500);
trafficLight = "yellow2";
} else {
setTimeout(yellow2,500);
trafficLight = "green";
}
}
var interval = setInterval(automatic,1000);
- Don't redeclare vars with
var
multiple times. - Use the
==
operator for statements. - Don't use brackets
()
if you using a named function as handler.
Solution 3:
this is working and tested. incorporates all previous comments.
<!DOCTYPE html><html><head></head><body><h2>Traffic Lights Program</h2><divclass="light"><imgsrc="Blank.png"style="width:100px;height:228px;"/></div><script>
trafficLight = "green";
var trafficLights = ["Red.png","RedYellow.png","Yellow.png","Green.png"]
functiongreen() {
document.images[0].src = trafficLights[3];
}
functionyellow() {
document.images[0].src = trafficLights[3];
}
functionredYellow() {
document.images[0].src = trafficLights[1];
}
functionred() {
document.images[0].src = trafficLights[0];
}
functionyellow2() {
document.images[0].src = trafficLights[2];
}
functionautomatic() {
if (trafficLight == "green") {
setTimeout(green(),500);
trafficLight = "yellow";
} elseif (trafficLight == "yellow") {
setTimeout(yellow(),500);
trafficLight = "redYellow";
} elseif (trafficLight == "redYellow") {
setTimeout(redYellow(),500);
trafficLight = "red";
} elseif (trafficLight == "red") {
setTimeout(red(),500);
trafficLight = "yellow2";
} else {
setTimeout(yellow2(),500);
trafficLight = "green";
}
}
setInterval(automatic,1000);
</script></body></html>
Post a Comment for "What's Going Wrong With My Timed Traffic Lights Program?"