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?
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 }); });
If you want to show a dialog while calculations are occuring, use setTimeout to call the long calculations after showing the dialog. If you want to show a progress bar, then you'll have to use a sequence of setTimeout calls at convenient points during the processing. When one ends, it updates the progress bar and calls the next one untill everything is done.
However, while any particular script is running, the UI will be blocked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With