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
Related
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;
}
});
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>
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
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.
I'm creating a counter and I'm having a hard time making it.
The goal of the counter is that for ever second passed a number will increase by 170.
As you can see below the number does not add up and is made on a new line, mostly because I dont know how to make it add up. Some thing like this clock from The Economist
<!DOCTYPE html>
<html>
<body>
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
<script>
function counterFunction() {
setTimeout(function () {
var text = "";
var i = 170;
while (i < 3500) {
text += "<br>The number is " + i;
i+=170;
}, 1000) }
document.getElementById("counter").innerHTML = text;
}
</script>
</body>
</html>
Any ideas on how I can make this and what is wrong with my code?
Don't use inline JavaScript (JavaScript inside HTML element attributes), it is horrible for maintainability and readability.
You seem to have a misconception about how timeouts, intervals and while loops work, what you want is an interval.
Define a count variable outside of the event listener function, then on each iteration of the interval increment the count variable by one and multiply that number by 170.
I added a little bit in there to hide the button once it has been clicked, just to stop the user from restarting the counter.
var clicker = document.getElementById('clicker');
var counter = document.getElementById('counter');
var count = 0;
clicker.onclick = function() {
setInterval(function () {
counter.textContent = "The number is " + ++count * 170;
}, 1000);
clicker.style.display = 'none';
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button id="clicker">See it now</button>
<p id="counter"></p>
http://jsfiddle.net/mblenton/Le4vxzrn/2/
function counterFunction() {
var text = ""; var i = 170; var delay = 0; var k = 1;
while (i < 3500) {
text = "The number is " + i;
i += 170;
delay = k * 1000;
doSetTimeout(text, delay);
k++;
}
}
function doSetTimeout(text, delay) {
setTimeout(function () {
document.getElementById("counter").textContent = text;
}, delay);
}
You need to use setInterval, not setTimeout`. Note that if you click the button, it will reset your timer.
You also need to declare var i and var text outside the scope of the Interval, or they will also be reset each iteration.
There were a few things wrong with your code. Among other things:
your i variable was declared in the wrong place to be reused
your closing braces were in the wrong place for the callback function
you were using a while loop, which runs synchronously, whereas you really want to just use a setInterval call.
This should work:
function counterFunction() {
var i = 170;
var text = "";
var interval = setInterval(function () {
text += "<br>The number is " + i;
i+=170;
document.getElementById("counter").innerHTML = text;
if (i >= 3500) {
clearInterval(interval);
}
}, 1000);
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
Ok so the adder variable should be declared outside of the timeout function, because if not you are replacing the value. and you should use setInterval
var p =0;
function counterFunction(){
setInterval(function(){ p+=170;
console.log('value of p '+p);
}, 3000);
}
if you dont want to roll your own here is a nice counter
http://keith-wood.name/countdown.html