setinterval - 有什么方法可以在触发新的 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
解决方案
您正在清除动画上的帧间隔,但您没有在每次后续调用 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)
推荐阅读
- vb.net - 如何制作我们自己的文件类型
- python - Python:Webdriver 获取 URL 列表、重复数据
- python - VsCode:在导入路径中查找文件和符号
- arrays - C中的自由指针数组
- ruby - 如果连接丢失,ActiveRecord 连接会发生什么情况
- javascript - 如何发出事件并将数组从模态组件发送到父级
- javascript - 为什么动态添加脚本元素时document.currentScript没有属性?
- python - 将行转换为列并在 pandas 中创建新列
- angular - 如何将ngFor索引传递给类变量以在全局范围ANGULAR 11中使用
- python - 仅显示嵌套 MongoDB 集合中的选定字段