Javascript rotating Images?
Question by titchyc: Javascript rotating Images?
how can I change 3 images on a html page several times, like a slot machine so that it scrolls and use a timer to make them change each time.
myimages = 0
machine= [
"images/bear.gif",
"images/dog.gif",
"images/cat.gif",
"images/goat.gif",
"images/sheep.gif",
"images/bird.gif",
"images/snake.gif",
"images/lizard.gif",
"images/lion.gif",
]
function random(animal)
{
myimages = Math.floor(Math.random() *
x= document.getElementById(animal)
x.src = drum[myimages]
return false
}
function move()
{
random(‘pic0′)
random(‘pic1′)
random(‘pic2′)
}
Best answer:
Answer by Martyr2
You might want to try investigating the function called setTimeout() which will allow you to set a timer to call a function after a specified number of seconds.
So how will it work? Well, when you first load the page you call your random function, at the end you setup a setTimeout() function which calls your random function again. Each time you call the random function you reset the pictures you want to change with the code you are using there.
function random(animal)
{
myimages = Math.floor(Math.random() *
x = document.getElementById( “animal” );
x.src = drum[myimages];
var t = setTimeout(“random(animal)”, 5000);
}
Now this is a basic function and largely untested, but you could easily add all three images in this one function and have the setTimeout call itself to change all three at the same time. Or you can create an animation by setting up another function that calls three different functions at different specified times with three setTimeout calls.
Check out the link provided below for some more examples of how you can do this. Remember the trick is to use the setTimeout to call a function in which itself has another setTimeout call (its a sort of recursion).
Hope this helps!
What do you think? Answer below!
Tags: Images, Javascript, rotating

August 27th, 2010 at 5:44 pm
Hey, you’ve come a long way!
(don’t use the number 8, use machine.length)
the trick is to use setTimeout, and setInterval
if you run each wheel independently , you can come up with some nice animation… but real slot machines rotate thru the pics in order, then stop on the lucky one!
I did a similar thing on my dog’s site, the pictures just rotate through. and they never stop… but a random timeout could stop the interval for each wheel!
http://jpassoc.com/junior