阻止函数运行两次

时间:2011-03-30 12:56:30

标签: javascript function

我有一个自动运行的幻灯片,您可以通过单击按钮跳到图像。

如果在图像静止时单击其中一个按钮,它可以正常工作,但如果在淡入淡出功能运行时单击它,它将运行两次函数,从而创建某种循环,最终将浏览器研磨成静止状态!

我知道我需要添加某种“isRunning”标志,但我不知道在哪里。

以下是jsfiddle的链接 - http://jsfiddle.net/N6F55/8/

代码也低于......

的javascript:

$(document).ready(function() {

var images=new Array();
var locationToRevealCount=6;
var nextimage=2;
var t;
var doubleclick;

addIcons();

function addIcons() {
    while (locationToRevealCount>0) {
        $("#extraImageButtons").append('<img class="galleryButtons" src="http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png" alt="'+locationToRevealCount+'" />');
        images[locationToRevealCount]='http://www.tombrennand.net/'+locationToRevealCount+'a.jpg';
        locationToRevealCount--;
    };
    $('.homeLeadContent').prepend('<img class="backgroundImage" src="http://www.tombrennand.net/1a.jpg" />');
    $("#extraImageButtons img.galleryButtons[alt*='1']").attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");
    runSlides();
}

function runSlides() {
    clearTimeout(t);
    t = setTimeout(doSlideshow,3000);
}

function doSlideshow() {
    if($('.backgroundImage').length!=0)
        $('.backgroundImage').fadeOut(500,function() {
            $('.backgroundImage').remove();
            slideshowFadeIn();
        });
    else
        slideshowFadeIn();
}

function slideshowFadeIn() {
    if(nextimage>=images.length) 
        nextimage=1;

    $("#extraImageButtons img.galleryButtons").attr("src","http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png");
    $("#extraImageButtons img.galleryButtons[alt*='"+nextimage+"']").attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");

    $('.homeLeadContent').prepend($('<img class="backgroundImage" src="'+images[nextimage]+'" style="display:none;">').fadeIn(500,function() {
        nextimage++;
        runSlides();

    }));
}

$("#extraImageButtons img.galleryButtons").live('click', function() {
    nextimage=$(this).attr("alt");
    $("#extraImageButtons img.galleryButtons").attr("src","http://www.steveszone.co.uk/images/button_sets/pink_square_button1n.png");
    $(this).attr("src","http://www.steveszone.co.uk/images/button_sets/black_square_button1n.png");
    clearTimeout(t);
    doSlideshow();
});
});

HTML:

<div class="homeLeadContent" style="width:965px;">

</div>
<div id="extraImageButtons"></div>

1 个答案:

答案 0 :(得分:1)

两项更改使我的工作更好:

  1. 在“额外图像按钮”处理程序中,调用“clearInterval()”,但应将其更改为“clearTimeout()”。
  2. 在设置另一个超时之前,我在“runSlides()”函数中添加了对“clearTimeout(t)”的另一个调用。
  3. 点击“点击我”按钮可能仍然会做一些奇怪的事情。

    编辑 - 以及here is my fork of the original jsfiddle而我认为它正在做正确的事情。除了正确调用“clearTimeout()”之外,我还更改了“doSlideshow()”中的代码,以便在添加其他图像之前清空内容<div>

相关问题