I need the images to change from one to another each time the button is pressed. I have tried using SetTimeout, setInterval etc and none of these seem to work? Im not sure what I'm doing wrong
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var myVar = setInterval(function() {
ChangeLights()
}, 1000);
}
}();
<button type="button" onclick="changeLights()">Change Lights</button>
You are calling ChangeLights instead of changeLights. But even if you call it right, you create an interval with calling the same function each 1000 ms. That means at the second call, it create a new interval and calls it again and the actual interval call the function as well.
Solution: Separate initializing of the interval and the function for doing the work.
Start with startLights and call changeLights in the interval.
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) {
index = 0;
}
console.log(index);
}
function startLights() {
setInterval(changeLights, 1000);
}
<button type="button" onclick="startLights()">Change Lights</button>
Error
changeLights() != ChangeLights()
Warning
Is the setInterval() placing
Not apply the setInterval() inside the click function.In each time loop time second's are reduced.so its change more lower time seconds.So use with setInterval with in click and color change was separate
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function change() {
index = index + 1;
if (index == list.length)
index = 0;
console.log(list[index])
}
function changeLights(){
var myVar = setInterval(function() {
change()
}, 1000);
}
<button type="button" onclick="changeLights()">Change Lights</button>
As above answers indicate - the call to the function needs to be outside it. One alteration I would suggest is to use the modulus operator (index % 3) which will allow a constant cycling of the images without the need for the if statement. This works because the modulus operator gives the remainder after dividing the number by the operator - so modulus %3 will mean that for example if index is three - the remainder is 0, 4 gives 1 5 gives 2 and then 6 is back at 0. So you have a perfect cycling count giving the three values 0,1, and 2 without having to check for each one.
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index +=1;
document.getElementById('imageSrc').textContent = 'Source: ' + list[index %3];
document.getElementById('lights').src = list[index %3];
}
var myVar = setInterval(function() {
changeLights()
}, 1000);
<p id="imageSrc"></p>
<img id = "lights"/>
Related
I want to get back to the start of the array but it keeps returning the second item in the array.
var counter = 0;
var srcArray = ["/images/e2450-1.png", "/images/e2450-2.png", "/images/e2450-3.png"];
function nextFunction() {
document.getElementById("chat-bubble").src = srcArray[++counter];
if (counter == 2) {
counter = 0;
};
return srcArray;
}
If anybody could help it would be great.
You are incrementing your counter before using it. try counter++.
++counter increment the counter than evaluate the expression.
counter++ evaluate the expression then increment the counter.
var counter = 0;
var srcArray = ["/images/e2450-1.png", "/images/e2450-2.png", "/images/e2450-3.png"];
function nextFunction() {
document.getElementById("chat-bubble").src = srcArray[counter++];
if (counter == 2) {
counter = 0;
}
return srcArray;
}
Array index starts from 0 and not 1. The below change should work
document.getElementById("chat-bubble").src = srcArray[counter++];
This will set srcArray[0] which is the 1st item in array and then increment the count to 1.
I am trying to make a counter that counts from 10 to 0 using JavaScript with a loop function and setInterval but this does not work for me:
function count() {
var i;
for (i = numbers.textContent; 0 <= i; i--) {
numbers.textContent = i;
}
}
setInterval(count, 1000);
<div id="countDown">10</div>
You are doing a for loop inside setInterval
var numbers = document.getElementById('countDown');
function count() {
var i;
if(numbers.textContent>0)
numbers.textContent=numbers.textContent-1;
else
clearInterval(handle);
/*for(i=numbers.textContent; 0<=i; i--){
console.log(i)
numbers.textContent= i;
}*/
}
var handle= setInterval(count, 1000);
<div id="countDown">10</div>
This should work:
parseInt(numbers.textContent)
And there are many more:
You need a global variable.
You don't need a for loop for this.
Change the condition.
<div id="countDown">10</div>
<script>
var numbers = document.getElementById('countDown');
var interval = setInterval(count, 1000);
function count() {
var count = parseInt(numbers.textContent);
count--;
if (count == 0) {
clearInterval(interval);
}
numbers.textContent = count;
}
</script>
If you want to see it by loops, you can do using setTimeout:
<div id="countDown">10</div>
<script>
var numbers = document.getElementById('countDown');
function count() {
var count = parseInt(numbers.textContent);
count--;
numbers.textContent = count;
}
for (var i = 1; i <= parseInt(numbers.textContent); i++)
setTimeout(count, 1000 * i);
</script>
the first time count is called, the for loop will run till numbers.textContent is 0(and it's so fast that your eyes just missed that change on the page), and the 2nd call, 3rd call is just iterate around 0, nothing is changed.
BTW, after your counting is finished(or maybe you should give it a stop condition, reference to the DOC), you should unregister the interval, cause it never end by default.
I have a simple setInterval function that is done inside of a for loop. My goal is that I want the function to run on each position in the array, and once it reaches the end, I want it to stop. However, this is not happening. The timeout function is continuing to run infinitely. Can anyone explain where I'm going wrong and what I need to do to fix this?
JS
Keyhole.bufferArray = [Keyhole.twoMileBuffer, Keyhole.fiveMileBuffer, Keyhole.tenMileBuffer, Keyhole.twentyFiveMileBuffer];
var ticker = -1;
for(var i = 0; i < Keyhole.bufferArray.length; i++){
var populateServices = setInterval(function(){
++ticker;
addBuffersToService(Keyhole, i);
if(ticker >= Keyhole.bufferArray.length - 1){
ticker = -1;
clearInterval(populateServices);
}
}, 1000)
}
function addBuffersToService(Keyhole, index){
console.log(Keyhole);
}
Because you have a for loop that is making an interval for every index of the array. You should not be using the for loop if you are looping over the array with the interval. Remove the for loop.
The problem is that you overwrite your interval handler in loop. I suggest you to kepp handlers in array and remove them according to iterator varialble:
var ticker = -1;
var populateServices = [];
for(var i = 0; i < Keyhole.bufferArray.length; i++){
populateServices[ticker + 1] = setInterval(function(){
...
clearInterval(populateServices[ticker + 1]);
ticker = -1;
Note that array identifiers should be positive numbers so you should add +1 inside handlers array.
And don't forget to set ticker to -1 after clearInterval invokation.
I have been trying to code a traffic light sequence that will loop through the images automatically. However, I have a small problem with the automatic changing. Could you help with where I am going wrong?
var images = ["red.png",
"redamber.png",
"orange.png",
"green.png"];
setTimeout("changelight()",1000);
var index = 0;
function changeImage()
{
document.getElementById("img").src= images[0];
}
Please check the Fiddle
Try this
var index = 0;
function changeImage()
{
if (index > 3) index = 0;
document.getElementById("img").src= images[index];
index++;
}
var images = ["red.png",
"redamber.png",
"orange.png",
"green.png"];
setInterval(changeImage,1000);
You probably intended
document.getElementById("img").src= images[index];
And make sure that index is updated
You were mostly there, but there were a couple of little things.
Firstly, you were calling a function called changeLight, but the function was called changeImage. You also need to change the image source attribute to images[index], and then increase that value each time.
The line index = (index + 1) % 4; adds 1 to index, but will only allow it to get as high as 3. If it reaches 4 then the % 4 at the end will set it to 0.
For reference, see the remainder description on this page
You were also using setTimeout which only runs once. If you use setInterval it works exactly the same but repeats.
var images = ["red.png",
"redamber.png",
"orange.png",
"green.png"];
setInterval(changeLight, 1000);
var index = 0;
function changeLight() {
document.getElementById("img").src = images[index];
index = (index + 1) % 4;
}
The only other thing that may be an issue is that I don't know if your image actually does have an ID of img. If it doesn't then you'll need to add that.
You did some typical beginner mistakes:
Your function name isn't related with the one in the timer.
You probably want an interval instead of a single timeout.
You have to use a querySelector to select a DOM by tag.
To go through an array you have to use variable increment combined with an if check.
Please read the doc's: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
var images = ["red.png", "redamber.png", "orange.png", "green.png"];
var index = 0;
setInterval(function(){
document.querySelector("img").src= images[index];
/* common - easy to understand - way:
if (index > images.length - 1) index = 0;
...
index++;
*/
index = index == images.length - 1 ? index = 0 : index + 1 // casual way - toggle bool -
console.log(index);
}, 1000);
Example: https://jsfiddle.net/27jygopz/
var images = ["red.png", "redamber.png", "orange.png", "green.png"];
setTimeout("changelight()",1000);
var index = 0;
function changeImage()
{
index = (index + 1) % 4;
document.getElementById("img").src= images[index];
}
I have a JSON array(?) of pairs of every state and a value associated with that state, it looks like the following below:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]
I need the page to shuffle through them without reloading the page
"AL 6" [wait x seconds] then "AK 3" [wait x seconds] then etc...
I need this to run continuously.
I never use any of these languages but was told that they were my best bet.
Could someone give me some guidance on this please.
Thank you in advance.
Here's a jsfiddle with setInterval execting a function that alternates between each state and displays it in a div:
http://jsfiddle.net/WD5Qj/1/
var states = '[{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}]';
json = jQuery.parseJSON(states);
var i = 0;
var cycle = function(){
$("#state").html(json[i].STATE + json[i].AMOUNT);
i = (i+1)%json.length;
}
var loop = setInterval(cycle, 500);
Alright, you'd need a function that does the rotation through the array, and a variable for keeping the current state (in both meanings of the word):
var stateIndex = 0;
function rotate() {
stateIndex++;
if(stateIndex >= states.length)
stateIndex = 0;
displayState(states[stateIndex]);
}
And you'd need an interval to perform the rotation:
var stateRotation = window.setInterval(rotate, 3000); // 3000ms = 3 sec
The stateRotation variable is an identifier of your interval. You may use that if you ever want to stop: window.clearInterval(stateRotation);
Now, the above code anticipates a function displayState which takes a state object and displays it. How that would look depends entirely on how you want your state to displayed. In its simplest form, something like this:
function displayState(state) {
$('#state-name').html(state.STATE);
$('#state-amount').html(state.AMOUNT);
}
As per your description, it might perhaps be something more like
$('#state-text').html(state.STATE + ' ' + state.AMOUNT);
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
var i = 0;
setInterval(function(){
var array_index = i % states.length;
$('#state').html( states[ array_index ]['STATE'] );
$('#state').html( states[ array_index ]['AMOUNT'] );
i++;
}, 2000);
Here's a fiddle.
function displayNextItem(index){
if (index === states.length)
displayNextItem(0);
$("#someDiv").text(states[index]["STATE"] + " " + states[index]["AMOUNT"]);
setTimeout(function() { displayNextItem(index + 1); }, 1000);
}
And then
displayNextItem(0);
var i = 0, l = states.length, timer, intervalLength = 5000;
timer = setInterval(function(){
if(i >= l){
clearInterval(timer);
}else{
alert(states[i++].STATE);
}
},intervalLength);
This implementation is waiting the AMOUNT number of seconds. If you want constant number of seconds then other answers are better :).
JavaScript:
var states = [{"STATE":"AL","AMOUNT":"6"}, {"STATE":"AK","AMOUNT":"3"}];
function iterate(index) {
var time = states[index].AMOUNT;
// replace the text with new one
$("#output").text(states[index].STATE + " " + time);
setTimeout(function() {
var next = (index + 1) % states.length;
iterate(next);
}, time * 1000);
}
iterate(0);
HERE is the code.