Note that there are some explanatory texts on larger screens.

plurals
  1. POSynchronous / asynchronous nature of browser rendering and javascript execution
    primarykey
    data
    text
    <p>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.</p> <pre><code>.processing { background-color: #ff0000; } &lt;div id="mydiv"&gt; Processing &lt;/div&gt; </code></pre> <p>Script:</p> <pre><code>$("#mydiv").addClass("processing"); // Do some long running processing $("#mydiv").removeClass("processing"); </code></pre> <p>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.</p> <p>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?</p> <p>And more importantly, what is the recommended way to achieve this effect? Do I have to result to using <code>setTimeout</code> 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.</p> <p>EDIT:</p> <p>JSFiddle: <a href="http://jsfiddle.net/SE8wD/5/" rel="nofollow">http://jsfiddle.net/SE8wD/5/</a></p> <p>(Note, you may need to tweak the number of loop iterations to give you a reasonable delay on your own PC)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload