用javascript清除间隔

时间:2012-12-21 12:36:32

标签: javascript jquery setinterval intervals

我制作了一段间隔的动画。这是我的剧本:

var count = 0;
var countSecond = -40;
function arrowAnimation() {
    if (count > 40) {
        clearInterval();
    }
    $('.list-what-we-do .arrow').css({
        top: (count++) + 'px'
    });
}
function arrowAnimationSecond() {
    if (countSecond > 0) {
        clearInterval();
    }
    $('.list-what-we-do .arrow').css({
        right: (countSecond++) + 'px'
    });
}

setInterval(arrowAnimation, 5);
setInterval(arrowAnimationSecond, 5);

现在我的问题。我怎么能停止间隔。我使用了clearInterval。但这不起作用。我怎样才能解决这个问题?谢谢你的帮助!

2 个答案:

答案 0 :(得分:5)

当您使用setIntervalsetTimeout时,返回值是引用;您将此引用传递给clearInterval以取消。

var foo = setTimeout(...);
clearTimeout(foo);

答案 1 :(得分:0)

您必须将setInterval方法的返回值分配给变量

然后您可以稍后使用clearInterval

清除它
var count = 0;
var countSecond = -40;

var interval = setInterval(arrowAnimation, 5);
var secondInterval = setInterval(arrowAnimationSecond, 5);

function arrowAnimation() {
    if (count > 40) {
        clearInterval(interval);
    }
    $('.list-what-we-do .arrow').css({
        top: (count++) + 'px'
    });
}
function arrowAnimationSecond() {
    if (countSecond > 0) {
        clearInterval(secondInterval);
    }
    $('.list-what-we-do .arrow').css({
        right: (countSecond++) + 'px'
    });
}