jQuery setInterval()的问题?

时间:2011-11-10 04:34:34

标签: javascript jquery image-rotation

我有一个用jQuery构建的图像滑块。它被设置为以7000毫秒的间隔滑动图像。有时候,有时候,有时候,滑块会以超高速滑动图像(幻灯片之间的间隔约为1秒)。我无法确定原因。请帮助!

使用滑块链接到网站:http://healthyhometech.com

    function slider() {
        $(".paging").hide();
        $(".paging a:first").addClass("active");

        var imageWidth = $(".window").width();
        var imageSum = $(".image_reel img").size();
        var imageReelWidth = imageWidth * imageSum;

        $(".image_reel").css({'width' : imageReelWidth});

        rotate = function(){
            var triggerID = $active.attr("rel") - 1; 
            var image_reelPosition = triggerID * imageWidth; 

            $(".paging a").removeClass('active'); 
            $active.addClass('active'); 

            $(".image_reel").animate({
            left: -image_reelPosition
            }, 500 );

        }; 

        rotateSwitch = function(){
            play = setInterval(function(){ 
             $active = $('.paging a.active').next(); 
                if ( $active.length === 0) { 
                $active = $('.paging a:first'); 
            }

                rotate(); 
            }, 7000); //Timer speed
        };

        rotateSwitch();

        $(".image_reel a").hover(function() {
        clearInterval(play); 
        }, function() {
        rotateSwitch(); 
        }); 


    };

2 个答案:

答案 0 :(得分:2)

setInterval存在一个至关重要的问题:它仍然在内存中!因此,您可能在测试时刷新页面,因此,为相同的过程创建各种setInterval,因此,有时,您看到程序执行速度更快(实际上,setInterval多次出现)。

我能够通过使用var“my-interval”= setInterval来解决类似的问题,并且在运行setInterval之前,检查它是否存在(非零)。如果是这样,那就杀掉它或者根本不[重新]运行:

var myInterval;
if (myInteval == undefined) myInterval = setInterval(function () {
    ...
    myInterval=12345;
},..);

答案 1 :(得分:0)

尝试增加代码的以下部分中的时间值:

$(".image_reel").animate({
        left: -image_reelPosition
        }, 500 ); //Here increase the value 500 to a value suitable to you, for example 1000, 2000 etc. anything you like. 

以毫秒为单位的值,定义动画速度。

[编辑]

好的,从我观察到的情况来看,我认为只有当您在选项卡中打开网页并继续处理其他选项卡时才能获得快速滑动问题,然后当您返回包含该页面的选项卡时,它会滑动快节奏的图像。如果你留在标签上,它就不会发生。我的猜测是您在 Chrome 浏览器中发现了此问题。

脚本中似乎没有任何问题,只有Chrome浏览器的工作方式。如果你在后台留下一个标签,chrome可能会暂停setInterval()函数,当你返回到页面时,它会运行它在后台的时间。所以这可能是Chrome浏览器的工作方式。代码没问题。