<!DOCTYPE html> <html> <title>test</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> .mySlides {display:none;} </style> <body> <h2 class="w3-center">Slideshow test</h2> <div class="w3-content w3-section" style="max-width:500px"> <img class="mySlides" src="1.jpg" style="width:100%"> <img class="mySlides" src="2.jpg" style="width:100%"> <img class="mySlides" src="3.jpg" style="width:100%"> <img class="mySlides" src="4.jpg" style="width:100%"> </div> <p id="demo"><p> <script> var Index = 0; var x = document.getElementsByClassName("mySlides"); (Index <4) ? setInterval(slide,500):display(Index-1); function slide() { var i; for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } Index++; document.getElementById('demo').innerHTML = Index-1; x[Index-1].style.display = "block"; } function display(n) { x[n].style.display = "block"; } </script> </body> </html>
I want to display a sequence of images by setInterval().In the end, there should display last image. Problem is after running, there is no image . I am sure the variable 'Index' still keep increasing by 1. I don't know why....
Your code needs clearInterval
method to stop the interval
. I've replaced your images
with divs
for demo purpose.
var index = 0; var x = document.getElementsByClassName("mySlides"); function displayNextSlide() { for (var i = 0; i < x.length; i++) { if (i === index) { x[i].style.display = "block"; } else { x[i].style.display = "none"; } } index++; if (index == x.length) { clearInterval(interval); } } displayNextSlide(); var interval = setInterval(displayNextSlide, 500)
<!DOCTYPE html> <html> <title>test</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> .mySlides { display: none; } </style> <body> <h2 class="w3-center">Slideshow test</h2> <div class="w3-content w3-section" style="max-width:500px"> <div class="mySlides" src="1.jpg" style="width:100%">1</div> <div class="mySlides" src="2.jpg" style="width:100%">2</div> <div class="mySlides" src="3.jpg" style="width:100%">3</div> <div class="mySlides" src="4.jpg" style="width:100%">4</div> </div>
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.