I have a processing that takes a few seconds, so I want to add a visual indicator during its execution.
.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 user interface would be updated. However, by running this in a browser (at least in Firefox), the div never stands out. Can someone explain to me why my my div is never highlighted? The class is added, processing is performed, and then the class is deleted; the user interface is not updated between them, and the user never sees a red background.
I know that JS is single-threaded, but I always assumed that browser rendering would be done synchronously when and when the DOM is updated. Is my assumption wrong?
And more importantly, what is the recommended way to achieve this effect? Should I use setTimeout
to make slow processing asynchronous and work with a callback? There should be a better way, since I really don't need asynchronous behavior here; I just want the user interface updated.
EDIT:
JSFiddle: http://jsfiddle.net/SE8wD/5/
(Note: you may need to adjust the number of iterations of the loop to give you a reasonable delay on your PC)
source share