Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 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 Answer

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

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...