在clearInterval之后再次启动setInterval

时间:2015-04-09 08:56:32

标签: jquery

我在这里有一个动画:http://jsfiddle.net/r55w2u23/

当我点击黄色容器时,动画将停止。但是当我点击广场再次开始移动时,它就无法工作了。我在代码中找不到什么错误。

$(document).ready(function() {
    var refreshIntervalId = setInterval(update, 1000);

    $('.square').click(function() {
        if (refreshIntervalId != undefined) {
            refreshIntervalId = setInterval(update, 1000);
        }
    });
$('#container').click(function() {
        if (refreshIntervalId != undefined) {
            clearInterval(refreshIntervalId);
        }
    });

});

function update() {
    $('#container').animate({ left:"+=20px"});
}

2 个答案:

答案 0 :(得分:3)

几乎没有问题

$(document).ready(function () {
    var refreshIntervalId = setInterval(update, 1000);

    $('.square').click(function (e) {
        //need to stop the propagation else the container click also will get triggered
        e.stopPropagation();
        //if undefined need to start the interval
        if (refreshIntervalId == undefined) {
            refreshIntervalId = setInterval(update, 1000);
        }
    });
    $('#container').click(function (e) {
        //if the timer is not defined there is no need to clear it
        if (refreshIntervalId != undefined) {
            clearInterval(refreshIntervalId);
            //just calling clear interval will not clear the value of the timer reference
            refreshIntervalId = undefined;
        }
    });

});

function update() {
    $('#container').animate({
        left: "+=20px"
    });
}

演示:Fiddle

答案 1 :(得分:1)

首先,您需要停止事件传播,或者您点击方块也会在容器上注册,然后再次停止。

e.stopPropagation();

(如Arun Johny,已经说过) 但也停止使用setIterval,insted做一个递归,以确保aniamtion已经结束 http://jsfiddle.net/r55w2u23/2/