javascript setInterval / onload - javascript

I'm referring to the accepted answer for Change image in HTML page every few seconds. In this code, the very first timer event/image change occurs 6 secs after loading (then every 3 secs as expected). Could anyone explain to a beginner like me why this is so?
Thanks.
EDIT: Sorry for that, my fault. Let me try to explain what I'd like to do in the first place. The code given shows first startpicture.jpg and then cycles through image1.jpg to image3.jpg. I just want it to cycle through image1.jpg to image3.jpg without a seperate start picture (or all 4 pictures, including startpicture.jpg). Therefore is replaced startpicture.jpg with image1.jpg which made me get the wrong impression that the first image change occurred after 6 secs.
Maybe someone can help me how to change this code to cycling through the pictures without a designated start picture.

As per your edit, you can simply remove the startpicture (or replace with image1), and initially call the displayNextImage function immediately, then start the interval:
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
//call immediately
displayNextImage();
//then start interval
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
<button onclick="displayPreviousImage()">Previous</button>
<button onclick="displayNextImage()">Next</button>
</body>
</html>

may be its time taken to load the images ,
you can load all the image first and then start changing,
var images= new Array();
for(var i=0;i<imagelocation.length;i++)
{
images[i]=new Image();
images[i].onload=function(){ if(i=imagelocation.length){changeImage();}}
images[i].src=imagelocation[i]; //image location is array containg link
}
function changeImage()
{
//what u had written earlier
}

Related

Javascript image slideshow using a for loop

i'm trying to cycle through 3 images using a for loop in javascript. Here is my code:
<img name="slide" width="300" height="300">
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
window.onload = changeImage;
Currently, only image 3 is displayed. Anyone know what i'm doing wrong here?
Yes - this is because your for loop run finishes instantly so there's no time for slides 1 and 2 to be shown.
Give this a try:
var currentImage = 0,
images = [
"https://unsplash.it/200/300?image=100",
"https://unsplash.it/200/300?image=101",
"https://unsplash.it/200/300?image=102"
];
function initSlideshow() {
setImage(0);
setInterval(function(){
nextImage();
},1000);
}
function nextImage() {
if(images.length === currentImage + 1){
currentImage = 0;
} else {
currentImage++;
}
setImage(currentImage);
}
function setImage(image) {
document.querySelectorAll('.slide')[0].src = images[image];
}
window.onload = initSlideshow();
Example: https://jsfiddle.net/vvbdwazc/
Currently, only image 3 is displayed. Anyone know what i'm doing wrong
here?
it's all being displayed but the reason why you can only see the 3rd image is because you're not pausing for a certain time before displaying the next image hence it seems like it's not working.
use setInterval() method to show each image after a specified time.
Example:
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
var myVar = setInterval(function(){ changeImage() }, 1000);
You may later wish to prevent the setInterval() method from executing any longer in that case have a look at clearInterval().
window.onload = changeImage; tells me you want to change the image on page load event? In other words, the image changes only upon page load (or refresh).
Since state is not maintained by default (eg local storage or session storage or cookies) your best bet would be to use a random generator to choose randomly. See Generating random whole numbers in JavaScript in a specific range?
This is because the for works so fast it gets quickly to the third image. You could use instead some setInterval like this:
<img id="slide" width="300" height="300">
<script>
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
var i = 0;
setInterval(function() {
var slide = document.querySelector("#slide"); //Select the img element by ID
slide.src = images[i++];
if(i > images.length - 1)
i = 0;
}, 1000); //Time in milliseconds
</script>
This will change constantly back to the first image when it reaches the last one.
Edit: Forgot to mention. setInterval works like a "repeater", it will work indefinitely until you clear it. To clear it you need to asign it to a variable and then use clearInterval passing the variable.
var interval = setInterval(function(){}, 1000) //example
clearInterval(interval);
Like so.

JavaScript while loop error: Unexpected token

So I have made a code for some coursework, the code is suppose to start a function on page load which will then run the function of changing the traffic light image on screen. It is suppose to keep on changing forever however the program crashes or fails to load when I try to run. Before you suggest the problem is that the variable used in the condition isnt changed, I have tried to change it in the following code. when I ran it in the chrome debugger this is the thing that came up; 'Uncaught SyntaxError: Unexpected token <'.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"r.jpg",
"randy.jpg",
"g.jpg",
"y.jpg"
];
var counter = 0;
function start() {
counter = counter + 1;
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=images[counter];
}
var a = 100;
function infinity() {
while (200>a) {
setTimeout(start(), 3000);
}
a = a - 25;
}
</script>
</body>
</html>
Instead of setting while loop and setTimeout, use setInterval. The below code will work I think. It will change the image 100 times
var url="http://www.hdwallpapers.in/thumbs/2017/";
var a=0,Handler;
var images = ["yosemite_national_park_winter_4k-t1.jpg","namib_coastal_desert_4k-t1.jpg","beach_dock-t1.jpg"];
var counter = 0;
function start() {
counter = counter + 1;
a++;
if(a>=100 && Handler)
clearInterval(Handler);
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=url+images[counter];
return;
}
function infinity() {
Handler=setInterval(start, 3000);
}
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="http://www.hdwallpapers.in/thumbs/2017/yosemite_national_park_winter_4k-t1.jpg">
<script>
</script>
</body>
</html>
I know that this question already has an answer, but i just figured that the following code might be a better and a relatively simpler way of doing it.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"red.JPG",
"green.jpg",
"randy.jpg",
"yellow.JPG"
];
function infinity() {
var counter = 0,
image = document.getElementById("trafficlight"),
a = 5,
timeoutInterval = 3000;
setInterval(function() {
counter++;
if(counter == images.length) counter=0;
if (a>=0) {
image.src=images[counter];
a--;
}else{
// this else case is in the event that the timeout
// variable is 1, which is essentially 1ms, which
// is bad as it would make your cpu usage go to a
// 100%
if (timeoutInterval <= Number.MAX_SAFE_INTEGER - 2) {
// the above if condition is to stop timeoutInterval
// from ever reaching 2^53 which would cause an
// overflow
timeoutInterval *= 2;
Math.pow(timeoutInterval, 20);
}
}
}, timeoutInterval);
}
</script>
</body>
</html>
Thanks!
P.S. my laptop is still hot from running your infinite loop code of an example

Manual traffic light conversion into automatic via Javascript

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going? Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>
To make this automatic, you can either put it in a loop, or you can use the setInterval function.
var interval = setInterval(nextLightClick, 1500);
This will loop indefinitely, running the function every 1500 milliseconds (1.5 seconds). If you want to stop it, you can simply say:
clearInterval(interval);
Here's an example -- note that I am changing the innerHTML, rather than the src, and I am using a div instead of image, but the logic will be exactly the same.
var tlight = new Array("1green.jpg","2yellow.jpg","3red.jpg");
var index = 0;
var tlightLen = tlight.length;
var image = document.getElementById('firstlight');
image.innerHTML = tlight[index];
var interval;
function startInterval() {
interval = setInterval(nextLightClick, 1500);
}
function stopInterval() {
clearInterval(interval);
}
function nextLightClick() {
index++;
if (index == tlightLen)
index = 0;
image.innerHTML = tlight[index];
}
<span id="firstlight"></span></br>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>

Problems with random images in array

var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log( eiImg );
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage );
var counter = eieren - 1;
function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
};
<html lang="en">
<head>
<!-- <link rel="stylesheet" type="text/css" href="css/style.css">-->
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img src="img/questionmark.png" id= "first" alt="questionmark" width="200" height= "300" onClick ="changeImage()">
<script type="text/javascript" src="js/eigame.js"></script>
</body>
</html>
I am new on this website and I'm having struggles with a project of mine. Let me explain what I want to make.
I have an array with 4 images. Every time the page refreshes, a random image (so a random image from the array) appears. I'm making a very simple game where you have to click on images of eggs with 1 crack, 2 cracks, 3 cracks and one where a chick is coming out of an egg. The goal of the game is to get all the chicks out of the eggs. So the page is refreshed and for example, the image with the egg with 2 cracks shows up. That means you have to click 2 times (array: img1(egg with 1 crack), img2(egg with 2 cracks), img3(egg with 3 cracks), img4(image with chick coming out the egg) to show the image with the chick out of the egg. At the end of the game (i still have to make a timer) all of the pictures have to be the chick coming out of the egg. So with I think with a For loop, it will check at the end of the game if all images are img4.
It's working a little bit, but there is a problem. When I refresh the page a random image shows up. For example img2. I have to click 2 times to get to the chick. But in my case, when i click, it changes first in to the first image of the array, img1. And then when you click it again it will go from img1 to 2 to 3 to 4 and if you click again to 1 again.
What I want is if the page for example shows img2, and you click on the image, it will go to the next image in the array. Not first go to img1 and then go to the next images.
Once that is fixed, I want the clickfunction to stop at the last image in the array. So if the last image in the array is shown, the chick out of the egg, you can't click anymore further. Now, when you click the chick picture, it goes back to the first image in the array.
Here is my code so far (I'm very new with javascript, I'm sorry for the many questions) I hope someone can help me with this, I've been stuck for days..
var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log(eiImg);
document.getElementsByTagName('img')[0].src = eiImg;
var counter=[0];
function changeImage(){
//Change image and increment counter
document.getElementById("first", "second").src=imgArray[counter++ % imgArray.length];
}
This is in my HTML:
<img src="img/questionmark.png" id= "first" alt="questionmark" width="200" height= "300" onClick ="changeImage()">
I made a Fiddle but it's not working on it. Gosh, I'm probably doing something wrong. Sorry!.. https://jsfiddle.net/mtjsd0bL/
I think that your problem is with counter++ in change image. Try set it to eiImg not to [0]
Something like this:
var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log( eiImg );
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage );
var counter = eieren - 1;
function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
}
Check my updated answer.

using onmouseover as

I have a continuous loop of alternating images that I would like to be able to interrupt and have display a new picture that corresponds with the current displayed picture using an onmouseover affect for as long as the mouse is on the image.
As an example to better describe my problem, I would like to have a bunch of images alternating on the screen every five seconds (which I can already do). Then when the mouseover event happens, have the images stop alternating and have a new image displayed that corresponds with the image that was just displayed (it will be another image that describes the image that was just being displayed). I also want the images to stop alternating while the mouse is over the images.
So far I can get the first image to display its corresponding image, but I can't seem to get the rest to work. Also I can't get the alternating images to stop while the mouse is still on the image.
Here's what I have so far:
<body>
<img src="image1.jpeg" alt="Image1" width="344" height="311" id="rotator" onmouseover="this.src='imageText1.jpeg'" onmouseout="this.src='image1.jpeg'">
<script type="text/javascript">
(function() {
var rotator = document.getElementById("rotator");
var imageDir = '';
var delayInSeconds = 5;
var images = ["image2.png", "image3.gif", "image4.png", "image5.jpeg","image6.gif", "image7.jpeg", "image1.jpeg"];
var num = 0;
if (rotator.onmouseover == )
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
if (rotator.onmouseover == )
{
}
we must check something in if conditon.
empty condition is a problem.please check it.

Categories

Resources