轮播图自动播放时怎么控制切换间隔时间?
我用原生JS写了个简单的轮播组件,但自动播放的切换速度太快了,想改成3秒换一张,试了改 setInterval 里的数值好像没生效,是不是哪里逻辑错了?
这是我的关键代码:
let currentIndex = 0;
const images = document.querySelectorAll('.slide');
setInterval(() => {
images[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % images.length;
images[currentIndex].classList.add('active');
}, 1000); // 这里改成3000也不行?
你得先停掉旧的,再重新开:
如果你想在页面加载后动态调整间隔(比如用户可以切换速度),这么写:
简单说就是:定时器一旦跑起来了,它的间隔就锁死了,想改必须重建。