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

Viewed 14075

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?

2 Answers
Related