有人可以解释一下为什么clearInterval
调用不起作用吗?
$(function() {
var width = 720;
var animationSpeed = 2000;
var currentSlide = 1;
var $slider = $("#slider");
var $slideContainer = $slider.find('.slides');
var $slides = $slideContainer.find('.slide')
var intervalID = function() {
if (currentSlide === $slides.length) {
for (currentSlide = 1; currentSlide < $slides.length; currentSlide++) {
$slideContainer.animate({
"margin-left": '+=' + width
}, animationSpeed).delay(1000);
}
}
if (currentSlide = 1) {
for (currentSlide = 1; currentSlide < $slides.length; currentSlide++) {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed).delay(1000);
}
}
};
function startSlider() {
setInterval(intervalID);
}
function stopSlider() {
clearInterval(intervalID);
}
$slider.on('mouseenter', stopSlider).on("mouseleave", startSlider);
startSlider();
`enter code here`
});
最佳答案
您需要捕获setInterval
的返回值并将其提供给clearInterval
。
var intervalId = setInterval(fn, duration);
clearInterval(intervalId);