简体   繁体   中英

Javascript slide show of images

I am working on a code to create a slide show of image using javascript. I want the image to change continuously after a certain time interval and also when clicked. Here's what I did-

<html>
<head>


<script type="text/javascript">
var image1 = new Image();
image1.src="1.jpg";
var image2 = new Image();
image2.src="1_1.jpg";
var image3 = new Image();
image3.src="1_1_1.jpg";
</script>



<img src="1.jpg" name="slide" width="200" height="200" onclick="changeimg()">
<script type="text/javascript">
var step = 1;

    function slideit() {
        document.images.slide.src = eval("image" + step + ".src");

        if (step < 3)
            step++
        else 
            step = 1

        setTimeout("slideit()", 2500);
    }


    slideit();

    function changeimg()
        {
            slideit();
        }
    </script>

    </head>

    </html> 

It's working fine but the speed increases every time I click on the image.. Any idea where the problem is?

Change image just needs to be calling the slideit function, and the timeout needs to be cleared. (Edit: Originally forgot about doubling timeouts)

var step = 1;
var timer;

    function slideit() {
        document.images.slide.src = eval("image" + step + ".src");

        if (step < 3)
            step++
        else 
            step = 1

        timer = setTimeout("slideit()", 2500);
    }


    slideit();

    function changeimg(){
            clearTimeout(timer)
            slideit();
        }

A better way to do this for future reusability my be to create an array of images, then using a similar logic to cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM