javascript在超时时突破for循环

时间:2014-01-20 10:19:47

标签: javascript for-loop settimeout

我有这段代码:

$(function(){
    var steps   = ["download","unpack","install","installed"];
    for(var i = 1; i <= steps.length; i++){
        setTimeout(function(){
            if(updater(steps[i]) === false) break; // if update fails
            else{
                var progress    = (i / steps.length) * 100;
                $("div#update div.progress div.progress-bar").animate({
                    width   : progress+"%"
                }).attr("aria-valuenow", progress);
            }
        , 5000)
    }
    if(steps.length === i){ // update is fully installed
        alertBox("success", "Congratulations, a new version of the SocialTab 3 has been installed.", 31556952000);
    }
    else{ // update failed
        alertBox("error", "<p>Update failed!</p><p>"+updateError+"</p>", 31556952000);
    }
});

当我这样做时,我不能使用break,因为它应该在for循环中使用,这不是因为我把它放在setTimeout函数中。 我想知道如何摆脱for循环并仍然延迟setTimeout函数中的代码。

2 个答案:

答案 0 :(得分:2)

试试这个:

$(function(){
    function StepUpdate(step)
    {
        var steps   = ["download","unpack","install","installed"];

        if (steps[step] != undefined)
        {
            setTimeout(function(){
                if(updater(steps[step]) === true)
                {
                    var progress    = (step / steps.length) * 100;
                    $("div#update div.progress div.progress-bar").animate({
                        width   : progress+"%"
                    }).attr("aria-valuenow", progress);
                    StepUpdate(step + 1);
                }
                else 
                {
                    // update failed
                    alertBox("error", "<p>Update failed!</p><p>"+updateError+"</p>", 31556952000);
                }
            }, 5000);
        }
        else 
        {
            alertBox("success", "Congratulations, a new version of the SocialTab 3 has been installed.", 31556952000);
        }
     }

     StepUpdate(0);
});

未测试过。

答案 1 :(得分:0)

您可以使用递归函数执行此操作,如下所示:

var steps = ["download","unpack","install","installed"];

function doUpdate( index ) {
    if( updater(steps[index]) === false) {
        alertBox( "error", "<p>Update failed!</p><p>"+updateError+"</p>", 31556952000 ); // if update fails
    }
    else{
        var progress = (index / steps.length) * 100;
        $( "div#update div.progress div.progress-bar" ).animate( {
            width : progress + "%"
        } ).attr("aria-valuenow", progress);
    }

    if( steps.length === i ) { 
        // update is fully installed
        alertBox("success", "Congratulations, a new version of the SocialTab 3 has been installed.", 31556952000);
    }
    else {
        doUpdate( index + 1 )
    }
}

doUpdate( 0 );