Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous / asynchronous nature of browser rendering and javascript execution

I have some processing that is going to take a few seconds so I want to add a visual indicator while it is in progress.

.processing
{
  background-color: #ff0000;
}

<div id="mydiv">
  Processing
</div>

Script:

$("#mydiv").addClass("processing");
// Do some long running processing
$("#mydiv").removeClass("processing");

I naively thought that the class would be applied to the div and the UI would be updated. However, running this in the browser (in Firefox at least) the div is never highlighted. Can someone explain to me why my my div never gets highlighted? The class is added, the processing takes place and then the class is removed; the UI is not updated in between and the user never sees the red background.

I know JS is single-threaded but I'd always presumed the browser rendering would run synchronously as and when the DOM is updated. Is my assumption incorrect?

And more importantly, what is the recommended way to achieve this effect? Do I have to result to using setTimeout to make the slow processing asynchronous and work with a callback? There must be a better way as I really don't have any need for async behaviour here; I just want the UI to refresh.

EDIT:

JSFiddle: http://jsfiddle.net/SE8wD/5/

(Note, you may need to tweak the number of loop iterations to give you a reasonable delay on your own PC)

like image 855
njr101 Avatar asked Mar 23 '12 10:03

njr101


1 Answers

You probably should put the processing out in a seperate event, like this;

$("#mydiv").addClass("processing");
setTimeout(function(){
   // This runs as a seperate event after
   // Do some long running processing
   $("#mydiv").removeClass("processing");
},1);

That way the browser should redraw the screen with the processing, while the long running step will kick off as a seperate event, and remove the processing message when done.

like image 152
Soren Avatar answered Oct 28 '22 14:10

Soren