首页 > 解决方案 > 有什么方法可以在触发新的 setInterval 之前清除之前的 setInterval

问题描述

这是运行 swiper 滑块的代码,当幻灯片移动或幻灯片更改时,我触发一个移动函数,该函数将 setInterval 方法触发到滑块上方的进度线以将其宽度增加到 100%,但是当我滑动滑块时在自动播放时间结束之前,它再次运行函数 move 并且这个新函数触发一个新的 setInterval 除非旧的还没有完成,所以我在这里有两个 setintervals 冲突。我无论如何都需要清除旧的,但是如果它的时间还没有结束。我希望你能理解并知道问题到底出在哪里。最后谢谢,对不起我的英语:)代码下面有一个链接请看

var autoplay = 5000;
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
watchSlidesProgress: true,
autoplay: autoplay,
onProgress: move
});
function move() {
var elem = document.getElementById("progress"); 
var width = 1;
var autoplayTime = autoplay / 100;
var id = setInterval(frame, autoplayTime);
function frame() {
    if (width >= 100) {
        clearInterval(id);
    } else {
        width++; 
        elem.style.width = width + '%'; 
      }
   }
}

链接 => https://codepen.io/shady-agmy/pen/OJVmNPw?editors=1010

标签: setintervalswiperclearinterval

解决方案


您正在清除动画上的帧间隔,但您没有在每次后续调用 move 时清除动画间隔

var autoplay = 5000;
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
watchSlidesProgress: true,
autoplay: autoplay,
onProgress: move
});
var previousid;
function move() {
    var elem = document.getElementById("progress"); 
    var width = 1;
    var autoplayTime = autoplay / 100;
    clearInterval(previousid);
    previousid = setInterval(function(_id) { return function() {
        if (width >= 100) {
            clearInterval(_id);
        } else {
            width++; 
            elem.style.width = width + '%'; 
        }
    }}(previousid), autoplayTime);

}
console.log(swiper)

推荐阅读