JavaScript Traffic light system using setInterval - javascript

I have make a traffic light system using javascript and used the setInterval to make it go by itself, however how can i make the timings different? for example i would like the red light and green light to stay on longer then amber and red amber.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<p>This is my very first JavaScript task</p>
<img id="traffic" src="red.png">
<button type="button" onclick="dosomething()">something magical will happen if you press me</button>
<script>
var list = ["red.png", "redamber.png", "green.png", "amber.png"];
var index = 0;
var timer = setInterval(dosomething, 3000)
function dosomething(){
index = index + 1;
if (index == list.length) index = 0
var image = document.getElementById('traffic');
image.src=list[index];
}
</script>
</body>
</html>

Here is an example using a weighted-time similar to what I was explaining in my comment. I don't have your images so I replaced them with text.
function changeColors(){
if (index >= list.length) index = 0;
let item = list[index];
if (!item.countdown) item.countdown = item.weight - 1;
else item.countdown = item.countdown - 1;
var image = document.getElementById('traffic');
image.innerHTML=list[index].color+'-'+item.countdown;
if (item.countdown == 0) index = index + 1;
}
var list = [
{color:"red.png", weight:1},
{color:"redamber.png", weight:3},
{color:"green.png", weight:2},
{color:"amber.png", weight:1}
];
var index = 0;
let btnChangeColors = document.getElementById('btnChangeColors');
btnChangeColors.onclick = function() {
var timer = setInterval(changeColors, 1000);
};
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<div id="traffic"/>
<button type="button" id="btnChangeColors">Start Traffic Light</button>

Related

Slider Images working correctly for right cursor but not left

I have created a website for a friend which includes a slideshow with his most recent Instagram posts. The slideshow has a right and left arrow cursor.
The right cursor is working how I want it to; it shows each image from the array upon each click, and keeps going regardless of how many times the user clicks the right cursor. When it reaches the last image in the array, it starts at the first image again due to an if statement put in place.
However, I am having trouble with the left cursor and I suspect it is the counter variable? With the current code, what happens is when I click the left cursor (with the page refreshed and without even clicking on the right cursor), it goes to the second image in the array index1, rather than the last. Then I click the left cursor again without any change happening, then when I click it the third time it goes to the last image in the array and works as it should until it reaches the second image in the array again - because after that it does not go to the first image, it skips the first image after another click of nothing happening and then goes to the last image in the array. Repeats itself in that manner (sorry for going so in-detail, but I want people to get an idea of whats happening here if the code doesn't help).
var sliderImages = [];
var counter = 1;
sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";
$("#right-arrow").click(function() {
$(".active").attr("src", sliderImages[counter]);
counter++;
$('#count').text(counter);
if (counter >= sliderImages.length) {
counter = 0;
}
});
$("#left-arrow").click(function() {
$(".active").attr("src", sliderImages[counter]);
counter--;
if (counter <= 0) {
counter = sliderImages.length
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="instagram-feed">
<div class="container">
<h2>INSTAGRAM GALLERY</h2>
<div class="insta-gallery">
<img src="images/left-arrow.png" class="arrow" id="left-arrow">
<img src="images/i1.png" class="active">
<img src="images/right-arrow.png" class="arrow" id="right-arrow">
</div>
</div>
<div class="clear"></div>
</section>
When your page loads, you set counter to 1. When you click the left-arrow button, the first thing you do is set the image to the counter value, and so you set the image to 1. (Remember, arrays are 0-indexed, meaning 1 refers to the second item).
You'd be better off if counter was referring to the current image, not trying to assume the upcoming one. See my comments in the modified code below for more information.
var sliderImages = [];
var counter = 0; //Start with first image instead of second
sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";
$("#right-arrow").click(function() {
counter++; //Moving forward by one
if (counter > sliderImages.length-1) counter = 0; //Wrap-around if we exceed length-1
$(".active").attr("src", sliderImages[counter]); //Update img src
});
$("#left-arrow").click(function() {
counter--; //Moving backward by one
if (counter < 0) counter = sliderImages.length-1; //Wrap-around if negative
$(".active").attr("src", sliderImages[counter]); //Update img src
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="instagram-feed">
<div class="container">
<h2>INSTAGRAM GALLERY</h2>
<div class="insta-gallery">
<img src="images/left-arrow.png" class="arrow" id="left-arrow">
<img src="http://via.placeholder.com/350x150" class="active">
<img src="images/right-arrow.png" class="arrow" id="right-arrow">
</div>
</div>
<div class="clear"></div>
</section>
Use a counter as if you're handling indexes, so set it initially at 0.
Here's the basic logic:
var sliderImages = [
"//placehold.it/100x100/0bf?text=O",
"//placehold.it/100x100/f0b?text=1",
"//placehold.it/100x100/0fb?text=2",
"//placehold.it/100x100/fb0?text=3",
"//placehold.it/100x100/b0f?text=4"
];
var n = sliderImages.length; // Total slides
var c = 0; // Counter
function anim () {
$("#mainImage").attr("src", sliderImages[c]);
}
$("#prev").on("click", function() {
--c; // Pre-decrement
if ( c < 0 ) { c = n-1; } // If lower than 0 - go to last slide
anim(); // animate
});
$("#next").on("click", function() {
++c; // Pre-increment
if ( c > n-1 ) { c = 0; } // If greater than num of slides - go to first slide
anim(); // animate
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="mainImage" src="//placehold.it/100x100/0bf?text=O">
<br>
<button id="prev">←</button>
<button id="next">→</button>
<span id="count"></span>
Or here's a neater extracted formula of the above:
var sliderImages = [
"//placehold.it/100x100/0bf?text=O",
"//placehold.it/100x100/f0b?text=1",
"//placehold.it/100x100/0fb?text=2",
"//placehold.it/100x100/fb0?text=3",
"//placehold.it/100x100/b0f?text=4"
];
var n = sliderImages.length; // Total slides
var c = 0; // Counter
function anim () {
c = c<0 ? n-1 : c%n; // Fix counter
$("#mainImage").attr("src", sliderImages[c]); // Animate (or whatever)
}
$("#prev, #next").on("click", function() {
c = this.id==="next" ? ++c : --c; // Increement or decrement
anim(); // Animate
});
// If you have bullets than you can simply do like:
$(".bullet").on("click", function() {
c = $(this).index();
anim();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="mainImage" src="//placehold.it/100x100/0bf?text=O">
<br>
<button id="prev">←</button>
<button id="next">→</button>
<span id="count"></span>
Updated your code a bit :
var sliderImages = [];
var counter = 0;
sliderImages[0] = "images/i1.png";
sliderImages[1] = "images/i2.png";
sliderImages[2] = "images/i3.png";
sliderImages[3] = "images/i4.png";
sliderImages[4] = "images/i5.png";
$("#right-arrow").click(function() {
counter++;
$(".active").attr("src", sliderImages[counter]);
$('#count').text(counter);
if (counter >= sliderImages.length) {
counter = 0;
}
});
$("#left-arrow").click(function() {
counter--;
$(".active").attr("src", sliderImages[counter]);
if (counter <= 0) {
counter = sliderImages.length - 1;
}
});

Image Changing Button using JavaScript

I had a look here and here for my answer but found that the code was far too long for such a simple process.
Below, my code shows a basic Image Changer by having the 'image' changed to the different .jpg's in an array, located in the same file.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
</script>
</body>
</html>
In theory, because I've embedded the script within the HTML it should work like a dream, but the image seems to get stuck on the yellow light. Is there a repeat button click phase I'm missing?
Thanks.
There is no need to use a loop. You can get reference to the button using document.getElementsByClassName("change-image")[0];. Then you can add an event lister to trigger on each button click.
Each time a user clicks you iterate through the array by one.
You could look at doing something like this:
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click',function() {
if(index === imageSources.length ) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
Here is the complete code, which works. If you inspect the img element you will see that it updates.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class="change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
</script>
</body>
</html>
Funny implementation -))
document.getElementById("changer").addEventListener("click", function(){
var i = document.getElementById("source");
var images = [
"http://lorempixel.com/400/200/sports",
"http://lorempixel.com/400/200/animals",
"http://lorempixel.com/400/200/nature"
];
var ord = parseInt(i.dataset.order);
nextImage = function(prev) {
return (prev+1 >= images.length ? (prev + 1)%images.length : prev+1);
}
document.getElementById("source").src = images[nextImage(ord)];
i.dataset.order = ord + 1;
})
<img id="source" data-order="0" src="http://lorempixel.com/400/200/sports">
<button id="changer">change</button>

Loop through images in HTML with a timer

This is my code, it only outputs the original red image and i don't understand how i'm supposed to make the code able to loop. Could someone help as I need this code desperately?
<!DOCTYPE html>
<html>
<head>
<h1> The traffic script</h1>
<script>
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
window.onload = changelights;
</script>
</head>
<body>
<img id="red" src="H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg">
</body>
</html>
Use SetInterval - this is not a loop like a for loop, etc. It is simply a block of code that will get triggered every x miliseconds.
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
setInterval(function(){changeLights()}, 4000);
This will call changeLights every 4 seconds. Also - be careful asking GCSE questions here especially the course work.
JavaScript has a built-in interval method, which can be used as a loop in this case.
var backgroundInterval = setInterval(function() {
changeLights();
if(index == (list.length - 1)) {
clearInterval(backgroundInterval); // stop the loop when it hits last image
}
}, 4000); // every 4000 ms, or 4s

Trying to make automated traffic lights

Hi Im trying to make a set of automated traffic lights but I can't get them to stop running. I have tried using window.clearInterval() but it won't work. Im doing this for my controlled assessment for my GCSE. I really don't know why this won't work so any help would be great. Thanks.
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src=asset[counter];
counter = counter + 1;
}
var toggle = 1
function timer() {
if (toggle === 1) {
var on = setInterval(changeLights,5000)
}
else {
window.clearInterval()
}
}
function stopTimer() {
toggle = toggle + 1
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
Try making the interval a global variable. Also you need to call self.clearInterval(interval). For example:
var interval;
function timer() {
interval = self.setInterval(changeLights, 5000);
}
function stopTimer() {
self.clearInterval(interval);
}
In your case:
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
var interval = null;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src = asset[counter];
image.alt = asset[counter]; // debug
counter = counter + 1;
}
function timer() {
if (!interval) {
interval = self.setInterval(changeLights, 1000);
}
}
function stopTimer() {
self.clearInterval(interval);
interval = null;
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
Note that I changed it in some ways, most notably removing the code having to do with toggle. This version also allows you to start it again without reloading the page, and prevents you from starting multiple intervals, which would require reloading the page to stop.

Traffic light Sequence Javascript

Here is my code for a traffic light's sequences. I was wondering how I could add a timer in to change the traffic light colour every 3 seconds, for example, when the button is clicked. Thanks!
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="light" src="./assets/red.jpg">
<button type="button" onclick="changeLights()">Change Lights</button>
<script>
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src = list[index];
}
</script>
</body>
</html>
Use the setInterval function.
The first parameter is the function you want to call and the second parameter is how often it should be called, in milliseconds.
var timer = setInterval(changeLights,3000);
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index]; }
var timer = setInterval(changeLights,3000);
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="light" src="./assets/red.jpg"> <button type="button"
onclick="changeLights()">Change Lights</button>
You can set a static timer with setTimeout(function, time);
In your case, if you want a repeating timer every 3 seconds constantly, you can have setTimeout run every time the changeLights() function ends
See w3schools article on timing
var timer;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index];
timer = setTimeout("changeLights", 3000);
}
With that change, once you start the lights, the function will repeat every 3 seconds.
The timer variable also alows you to stop the timer (perhaps in your case with another button) with:
clearTimeout(timer);
Hope this helps

Categories