Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 291
Chris Farmer Avatar asked Aug 08 '11 23:08

Chris Farmer


2 Answers

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 });  }); 
like image 128
Mrchief Avatar answered Sep 30 '22 07:09

Mrchief


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.

like image 27
RobG Avatar answered Sep 30 '22 09:09

RobG