My goal is to create a traffic light. I want to loop through the colors of the lights (red, orange, green, orange, then back to red again) with a 10 second wait after the red and green images are displayed, and a 2 second wait after the orange image is displayed. This needs to be looped with no user input.
To implement the wait, I tried to use setTimeout
, but my loop does not seem to run.
var trafficLights = ["RedLight.jpg", "RedOrangelight.jpg", "GreenLight.jpg", "OrangeLight.jpg"], waitTime = ["10000", "2000", "10000", "2000"], count = 0, x = 1; while (x=1) { setTimeout(waitTime[count]); document.getElementById("RedLight").src = trafficLights[count]; count += 1; if (count = 3) { count = 0; } }
<img id="RedLight" src="RedLight.jpg">
Use window.setInterval()
.
You can have your setInterval occur every second, and keep track of a variable that you increment every second. If the value is 1, change the image to red. If it's 3 (two seconds later), change the image to red-orange, and so on. And of course, when the value is 8, reset it to zero.
I think to get you on the right track, try changing the items in the waitTime
array to integers. Then, in your if statement, use ===
to check for equality. setTimeout
also takes in two arguments. An anonymous function, then then wait time. In general, I would avoid infinite loops. Can you make an exit condition for the while
loop? Take a look at my code below:
<script>
var trafficLights = ["RedLight.jpg", "RedOrangelight.jpg", "GreenLight.jpg", "OrangeLight.jpg"];
var waitTime = [10000, 2000, 10000, 2000];
count = 0;
x=1;
while (x === 1) {
setTimeout(() => {}, waitTime[count]);
document.getElementById("RedLight").src= trafficLights[count];
count+=1;
if (count === 3){
count = 0
};
};
</script>
<!DOCTYPE html>
<html>
<head>
<title> Images </title>
<meta charset="utf-8">
</head>
<body>
<script>
var elem = document.createElement('img');
document.body.appendChild(elem);
elem.style.cssText = 'width: 640px; height:360px;';
var trafficLights = ['RedLight.jpg', 'RedOrangelight.jpg', 'GreenLight.jpg', 'OrangeLight.jpg'],
waitTime = ['10000', '2000', '10000', '2000'],
i = 0;
(function fn()
{
elem.src = trafficLights[i];
setTimeout( function()
{
i = ( i + 1 ) % waitTime.length;
fn()
}, waitTime[ i ] )
}())
</script>
</body>
</html>
You may do as follows;
function runLights(a, i = 0){ console.log(a[i].color); setTimeout(runLights, a[i].dur, a, ++i%a.length); } var tl = [{color: "red", dur: 1000}, {color: "yellow", dur: 200}, {color: "green", dur: 1000}, {color: "yellow", dur: 200}]; runLights(tl);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.