首页 文章

SetInterval,然后是clearInterval,然后再次设置setInterval

提问于
浏览
0

我的滑块代码有问题 .

在这里,我定义了一个函数,根据有多少元素来设置滑块的动画(元素越多,它应该滑动的次数越多):

var animateSlider = function() {

        var howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;


        var repeatSlider = function() {
            howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;
            for (i=0;i<howManyTimes;i++) {
            // looped code
            $(".portfolio-slider").delay(2000).animate({
                        marginLeft: - (slideDistance * (i+1) )
                    }, 500);

            console.log(howManyTimes);
        }
        $(".portfolio-slider").delay(2000).animate({
                        marginLeft: 0
                    }, 500);
    }

    // and this is where I set the interval for sliding: 

    var intervalId;
    var intervalId = function() {
        setInterval(repeatSlider,howManyTimes * 500);
    }
    intervalId();

    // here's where I tried putting:
   // clearInterval(intervalId)
   // just to see if it clears it, but it didn't, the code interval just kept on replaying.

    }

如果autoplay设置为true,我在这里启动滑块:

// fires the slider if autoplay option is set to true
    if (autoplay) {
    animateSlider();
        }

这就是当我点击一个带有“.filter”类的按钮时会发生什么 - 它会过滤元素(代码被移除,因为它工作而不是我想要关注的)然后启动animateSlider函数以便它可以重新计算元素和它应该滑动的次数:

$('.filter').click(function(){
        // it does some stuff and then animates the slider again so it recalculates the widths and number of times it's supposed to slide:

        animateSlider();
    });

问题是我不认为它重新启动该功能,而是一次又一次地触发它并且它不会重新计算滑块滑动的次数(所以当我过滤元素时,它会滑动空幻灯片以及元件) .

我知道clearInterval()函数,但我已经尝试将它放在setInterval下但没有成功 .

理想的行为应该是 - 滑块滑动,点击“.filter”后,间隔停止并重新启动新的宽度和元素数量(而不是多次激发而不停止) .

这是我试图解决的第二天,我真的很感激一些帮助 .

1 回答

  • 0

    正如Will Jenkins所说,你需要返回setInterval()来获取创建的区间函数的引用 . 您的包装器功能实际上不会返回任何内容 . 你可以这样做:

    var intervalId = function() { 
        return setInterval(repeatSlider,howManyTimes * 500); 
    }
    

    要么

    var intervalId = setInterval(repeatSlider,howManyTimes * 500);
    

相关问题