是否有任何方法可以在触发新的setInterval之前清除以前的setInterval

问题描述 投票:0回答:1

这是运行滑动滑块的代码,当幻灯片移动或更改幻灯片时,我会触发移动功能,该功能会向滑块上方的进度线触发setInterval方法,以将其宽度增加到100%,但是当我滑动时在自动播放时间结束之前,滑块再次运行该函数,并且该新函数会触发一个新的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

setinterval swiper clearinterval
1个回答
0
投票

您正在清除动画中的帧间隔,但没有在随后的每次移动调用中清除动画间隔

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)
© www.soinside.com 2019 - 2024. All rights reserved.