title: Is there a way to force a reflow before a long-running JavaScript operation?
body: <p>Ready to face the backlash as I'm aware that this is an oft-asked question here, and fully aware that there are "much better" ways of accomplishing what I want to achieve...</p>
  
  <p>I have a long running JavaScript operation in a function which can take up to 10 seconds to run. I have a "loading div" that I can show and hide at will. Normally this show/hide operation works very quickly but if I attempt to do so in the same call chain as my long running function, the browser does not get chance to reflow and show the loading div before it is locked up by the long running function.</p>
  
  <p>I have tried:</p>
  
  <p>1 - just showing the div then calling the function:</p>
  
  <pre><code>$('#loadingDiv').show();
  longRunningFunction();
  </code></pre>
  
  <p>2 - showing the div then calling the long running function inside a setTimeout to be executed after the current function has finished:</p>
  
  <pre><code>$('#loadingDiv').show();
  setTimeout(function(){longRunningFunction();}, 0);
  </code></pre>
  
  <p>3 - same as 2 but with a longer timeout:</p>
  
  <pre><code>$('#loadingDiv').show();
  setTimeout(function(){longRunningFunction();}, 100);
  </code></pre>
  
  <p>With an even longer timeout (say, 5000 milliseconds) I am able to get the loading screen to show and my long running function to execute properly - but obviously this adds to the execution time and I guess won't be cross-browser compatible (it just so happens that the browser I am using happens to do a repaint in those XXXX milliseconds - another browser may not?)</p>
  
  <p>I've also tried a mish mash of tricks I've seen on SO and elsewhere to do with changing the <code>offsetLeft</code> / <code>offsetTop</code> on divs on the page, changing <code>self.status</code>, but everything I do seems to have the same effect: lock up the browser for a few seconds, with the old content on the page, then show the loading div once the long running function has finished.</p>
  
  <p>I know what I'm doing is "wrong" but it is what I want to do for the moment - ultimately I will:<br>
  1) Break this code down into smaller chunks<br>
  2) Potentially move it into a Web Worker<br>
  3) Speed it up so that it does not take so long and doesn't lock up the browser</p>
  
  <p>But <em>for now</em> can anyone suggest an easy way of forcing that "loading div" to be shown to the user before my long running operation runs?</p>