jQuery AJAX loop to refresh jQueryUI ProgressBar

前端 未结 2 1374
梦毁少年i
梦毁少年i 2020-12-15 01:31

I\'ve got a jQueryUI progressbar that should show the percentage of a query done. Oracle has a nice system table that lets you see operations that will take more than 10 se

2条回答
  •  旧巷少年郎
    2020-12-15 02:19

    Instead of setTimeout(GetProgress(), 3000), you would want:

    function StartLoop(){
        for (var i = 0; i < 100; i++) {
            setTimeout(GetProgress(), 3000*i);
        }
    }
    

    Otherwise, all 100 will fire off after 3 seconds. Instead, you want 0, 3000, 6000, 9000, etc., i.e. 3000*i;

    Better, you could use setInterval and clearInterval:

    var myInterval = setInterval(GetProgress(), 3000);
    

    and in the callback, do:

    $.ajax({
        url: "query.aspx/GetProgress",
        success: function (msg) {
            var data = $.parseJSON(msg.d);
            $("#pbrQuery").progressbar("value", data.value);
    
            if (data.value == 100) {
                isDone = true;
                clearInterval(myInterval);
            }          
        }
    });
    

    clearInterval will stop it from calling GetProgress() again. Using the setInterval method means you don't have to know how many poll loops you need up front. It will simply continue until you are done.

    Or better yet, you can call GetProgress() from the ajax callback, with the advantage that it will only poll again once you have a response from your query:

    function GetProgress() {
        $.ajax({
            url: "query.aspx/GetProgress",
            success: function (msg) {
                var data = $.parseJSON(msg.d);
                $("#pbrQuery").progressbar("value", data.value);
    
                if (data.value == 100) {
                    isDone = true;
                } else {
                    setTimeout(GetProgress(), 2000);
                }
            }
        });
    }
    

    Then just call GetProgress() once to initiate the loop.

提交回复
热议问题