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

时间:2016-08-04 10:19:30

标签: javascript jquery setinterval clearinterval

我的滑码有问题。

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

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();
        }

当我点击带有&#34; .filter&#34;的按钮时会发生什么? class - 它过滤元素(代码被删除,因为它工作,它不是我想要关注的),然后启动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下但没有成功。

理想的行为应该是 - 滑块滑动,点击&#34; .filter&#34;间隔停止并以新的宽度和元素数重新启动(而不是多次激活而不停止)。

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

1 个答案:

答案 0 :(得分:0)

正如Will Jenkins所说,你需要返回setInterval()来获取创建的区间函数的引用。你的包装功能实际上并没有返回任何东西。你可以这样做:

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

var intervalId = setInterval(repeatSlider,howManyTimes * 500);
相关问题