簡體   English   中英

javascript超時退出for循環

[英]javascript break out of for loop with timeout

我有以下代碼:

$(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函數中的代碼。

嘗試這個:

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

沒有測試。

您可以使用遞歸函數執行此操作,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM