Using setTimeout - how to pass parameters?
I am trying to create a slideshow with pause between slides. So I am trying to use the setTimeout statement as shown below. This is written to replace 2.jpg with 1.jpg with a 10 second pause when the button is pressed. But now it works. Can someone help me. Thank.
<html>
<head>
<script type="text/javascript">
var t;
function swap(newImage) {
var fileName=newImage.toString()+".jpg"
document.slideshow.src=fileName
t=setTimeout("swap()",10000)
}
</script>
</head>
<body>
<img name="slideshow" src="1.jpg" width="450" height="335" />
<br /><br />
<input type="button" onClick="swap('2')" value="Change image" />
<br /><br />
</body>
</html>
source to share
There are a couple of things here. First, its skip code, which should be evaluated in the first parameter to setTimeout , is not recommended. It's better to do a callback instead:
setTimeout(function() { swap(); },10000);
//Or
setTimeout(swap,10000); //Passing the actual function as the callback
Second, you call the swap () method with no parameters inside the timeout. It should pass in the new filename of the image (perhaps by declaring an array of filenames) or check if this option is set or not.
function swap(newImage,element) {
if(newImage) {
var fileName = newImage.toString()+".jpg";
element.src = fileName;
}
t=setTimeout(this,10000)
}
This function will obviously do nothing after the first run (since no new image file names are provided). Using an array, you can iterate over multiple filenames:
var images = ['1.jpg','2.jpg','3.jpg'];
var slideshow = function(element, images, index) {
if(!index || ( (index + 1) > images.length) ) index = 0;
element.src = images[index];
t = setTimeout(function(){
slideshow(element, images, index + 1);
},10000)
};
//Fetch the image element the slideshow is running on
var element = document.slideshow;
slideshow(element, images);
This will continue to switch between images in the array until the timeout is canceled.
source to share
Javascript is not required to do slideshow. All you have to do is place each image on a separate page and then add this single line at the top of each page in the <head> section:
<meta http-equiv="refresh" content="10;url=NextPage.html"/>
"10" is the number of seconds to wait before moving to the next page, and "NextPage.html" is the link to the page that contains the next image to display.
source to share