Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

jquery - How to force UI updates in the browser while lengthy javascript calculations are in progress?

I have one place in a web app where I'm doing a lot of calculations in JavaScript in the browser. They may take from a less than a second to about a minute to run, and I would like to show a progress dialog during this step, but the dialog doesn't show until after my calculations are complete. I started by just trying to show a jquery dialog:

HTML:

<input type="button" id="startwork" value="Start working">

<div id="dialog" title="My dialog">
    This should show up immediately on clicking the button.
</div>

Script:

$(function() {

    $("#startwork").click(function () {
        $("#dialog").dialog("open");
        // Do some lengthy calculations
        for (var i=0; i<1000000000; i++) {
            var foo = Math.random();   
        }
        $("#dialog").dialog("close");
        alert("done");
    });

    $("#dialog").dialog({ autoOpen: false });

});

What can I do to force the UI to update prior to the start of the calculations and at defined intervals during the calculations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrap your lengthy calculations inside a setTimeout:

setTimeout(function() {
// some length calculations
}, 0);

There should be no more script after setTimeout.

$(function() {

    $("#startwork").click(function () {
        $("#dialog").dialog("open");
        setTimeout(function() {
            // some length calculations
            for (var i=0; i<1000000000; i++) {
                var foo = Math.random();   
            }
            $("#dialog").dialog("close");
            alert("done");
        }, 0);
    });

    $("#dialog").dialog({ autoOpen: false });

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...