停止setTimeout循环当它到达列表的末尾时

时间:2011-02-12 23:26:05

标签: jquery

我有一个循环遍历一堆列表项的脚本;添加/删除每个。因为现在它只是无休止地循环,我怎么能改变这个脚本以便它到达最后一个列表项时停止?

http://jsfiddle.net/bizarroZ/YyDjW/

<style type="text/css" media="screen">
li {display:none;} .go {color:green;display:block}
</style>

<ul>
<li>First Slide</li>
<li>Second Slide</li>
<li>Third Slide</li>
<li>Fourth Slide</li>
<li>Fifth Slide</li>
<li>Sixth Slide</li>
</ul>

<a href="#" class="go-button">GO!</a>

<script type="text/javascript" charset="utf-8">

 $(".go-button").click(function() {

 $("li:nth-of-type(1)").addClass("go"); 

var index = 0;
var length = $("ul").children().length;
var delays = [
        1000,
        1500,
        2000,
        2500,
        3000,
        15000
        ];

function delayNext()
{
    setTimeout(function() {
    $("ul li:eq(" + index +  ")").addClass("go").siblings().removeClass("go");
        index++;

        if (index == length)
            index = 0;

           delayNext();
        }, delays[index]);
   }

    delayNext();
 });
</script>

2 个答案:

答案 0 :(得分:1)

在delayNext()内检查index == length并立即返回而不是调用setTimeout应该这样做。

function delayNext()
{
    if (index == length)
        return;
    setTimeout(function() {
        $("ul li:eq(" + index + ")").addClass("go").siblings().removeClass("go");
        index++;

        delayNext();
    }, delays[index]);
}

答案 1 :(得分:1)

您可以在这样的循环中简单地添加六个setTimeout调用:

var li = $('ul li'),
    delays = [1000,1500,2000,2500,3000,15000];

function sumPrev(array, index){
    var sum = 0;
    for(var i = 0; i < index; i++){
        sum += array[i];
    }
    return sum;
}

li.each(function(i){
    setTimeout(function($ele){
        $ele.addClass("go").siblings().removeClass("go");
    }, sumPrev(delays, i), $(this));
});

请参阅:http://jsfiddle.net/V5mRv/1/