Sunday, March 6, 2011

Use of setTimeout

I am trying to develop a slideshow with a pause between slides. So I'm trying to use the setTimeout statement as shown below. This is written to swap 2.jpg for 1.jpg with a pause of 10 seconds on clicking the button. But it does now work. Can anyone help me. Thanks.

<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>
From stackoverflow
  • Your swap function requires a parameter, so it won't work with setTimeout.

    Strelok : oh yeah lol :) that would do it actually :)
  • There are a couple of things wrong here. First, its passing code to be eval'ed in the first parameter of setTimeout is not recommended. Better pass a callback instead:

     setTimeout(function() { swap(); },10000);
     //Or
     setTimeout(swap,10000); //Passing the actual function as the callback
    

    Second, you are calling the swap() method without parameters inside the timeout. It should pass in a new image filename (perhaps by declaring an array of filenames), or check whether the parameter is set or not.

    function swap(newImage,element) { 
       if(newImage) {
           var fileName = newImage.toString()+".jpg"; 
           element.src = fileName;
       }
       t=setTimeout(this,10000) 
    }
    

    This function obviously won't do anything after the first run (since no new image filenames are supplied). Using an array you could iterate over several 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 switching between the images in the array until the timeout is canceled.

    nickf : setTimeout can accept a string as the first parameter. that string gets eval()'d so his method would work, if not for forgetting to pass the parameter.
    Eran Galperin : You are right, though it is not recommended. Edited
  • Javascript isn't necessary to do a slideshow. All you have to do is put each image into a separate page, then add this single line to 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 going to the next page, and "NextPage.html" is the link to the page containing the next image to display.

0 comments:

Post a Comment