开发者

Stopping setTimeout Loop When it reaches end of list

I have a script that that cycles through a bunch of list-items; adding/removing to each one. As it is right now it just loops endlessly, how could I alter this script so that it stops when it reaches the last list-item?

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").chil开发者_JAVA百科dren().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>


You can simply add six setTimeout calls in a loop like this instead:

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));
});

See: http://jsfiddle.net/V5mRv/1/


Having a check for index == length just inside the delayNext() and return right away instead of calling setTimeout should do it.

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜