如何退出jquery中定义的setInterval函数

时间:2010-09-14 16:40:24

标签: jquery function exit

我有这个javascript代码:

        var step = 8;                 // How many pixels to move per step
        var current = -1920;            // The current pixel row
        var imageWidth = 1920;        // Background image width
        var headerWidth = 960;        // How wide the header is.

        function slide_in(){
            //Go to next pixel row.
            current += step;

            //Set the CSS of the header.
            $('#bgfade').css("background-position",current+"px 0");

            if(current==0) alert('stop');
        }

        //Calls the scrolling function repeatedly
        $('#bgfade').click(function(){        
            var init = setInterval("slide_in()", 1);
        });

这使背景幻灯片。我想在var current = 0时退出,并让背景在那个位置。

感谢

1 个答案:

答案 0 :(得分:0)

您需要使用clearInterval(),如下所示:

var step = 8;                 // How many pixels to move per step
var current = -1920;            // The current pixel row
var imageWidth = 1920;        // Background image width
var headerWidth = 960;        // How wide the header is.
var init;

function slide_in(){
    //Go to next pixel row.
    current += step;

    //Set the CSS of the header.
    $('#bgfade').css("background-position",current+"px 0");

    if(current==0) clearInterval(init);
}

//Calls the scrolling function repeatedly
$('#bgfade').click(function(){        
    init = setInterval(slide_in, 1);
});

此处的其他更改是范围,因此计时器ID可用于其他功能,并且不会将字符串传递给setInterval()以避免任何其他潜在问题。

相关问题