我如何在jQuery中的函数之外调用clearInterval? setInterval之外

问题描述:

    function iPadMovie(id) {
    $(function () {
        var i = 1;
        var interval = setInterval(function () {
            jQuery('.animationMax img').attr({
                src: 'http://jdsports.scene7.com/is/image/JDSports/127932jd' + ('0' + i).slice(-2) + '?hei=255&wid=427&resmode=sharp&op_usm=1.1,0.5,0,0&defaultImage=JDSports/sizeImageMissing'
            });
            i++;
            if (i === 28) i = 1;
        }, 100);
    });
}

function playIpad(){
    iPadMovie();
}


function stopIpad(){
    clearInterval = interval;
}

您可以在这里看到小提琴: http://jsfiddle.net/Vv2u3/15/ 我希望能够停止播放电影并重新启动它。当然我可以在方法之外使用clearInterval?

You can see the fiddle here: http://jsfiddle.net/Vv2u3/15/ I want to be able to stop the movie and restart it if they press play. Surely I can use clearInterval outside the method?

下面是示例

Here is example link.

var interval;

function iPadMovie(id) {
    $(function () {
        var i = 1;
        interval = setInterval(function () {
            jQuery('.animationMax img').attr({
                src: 'http://jdsports.scene7.com/is/image/JDSports/127932jd' + ('0' + i).slice(-2) + '?hei=255&wid=427&resmode=sharp&op_usm=1.1,0.5,0,0&defaultImage=JDSports/sizeImageMissing'
            });
            i++;
            if (i === 28) i = 1;
        }, 100);
    });
}

function playIpad(){
    iPadMovie();
}

这里有点解释。
首先,你的区间变量(它是通过setInterval返回的回调函数的实际处理程序)在 iPadMovie()函数之外是不可见的,所以区间变量应该在此函数之外声明。
其次,您应该在 stopIpad()函数内调用 clearInterval(处理程序)函数。更多信息可以此处

Little bit explanation here. First of all, your interval variable, (which is actual handler for returned callback function by setInterval) is not visible outside of iPadMovie() function so interval variable should be declared outside of this function. Second you should call clearInterval(handler) function inside of stopIpad() function. More information can be founded here.

function stopIpad(){
    clearInterval(interval);
}