js利用setInterval() clearInterval()函数实现轮播图效果的代码
时间: 2023-10-21 12:13:28 浏览: 75
利用js来实现轮播图
Sure, here is an example of implementing a slideshow with setInterval() and clearInterval() functions in JavaScript:
First, set up an array of image sources and a variable to keep track of the current index:
```
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var currentIndex = 0;
```
Then, define a function to update the image every few seconds using setInterval():
```
function startSlideshow() {
setInterval(function() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
document.getElementById('slideshow').src = images[currentIndex];
}, 3000);
}
```
Finally, to stop the slideshow, use clearInterval() and pass in the interval ID returned by setInterval():
```
var intervalId = startSlideshow(); // start the slideshow and save the interval ID
clearInterval(intervalId); // stop the slideshow
```
Note: This is just an example and there are many ways to implement a slideshow in JavaScript. Also, please let me know if you have any further questions!
阅读全文