javascript - jQuery hide() and show() not immediately run when reversed later in the function -


i'm using jquery's .hide() , .show() functions show loading message while potentially long synchronous webservice call executes.

when clicking button in below snippet, expect text "some data" replaced "loading..." , go "some other data" after 5 seconds.

as can see, not happens:

function run_test() {      $('#test1').hide();      $('#test2').show();            long_synchronous_function_call()            $('#test2').hide();      $('#test1').show();  }    function long_synchronous_function_call() {      $('#test1').html('<p>some other data</p>');      var date = new date();  	while ((new date()) - date <= 5000) {}  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>  <div id="test1">      <p>some data</p>  </div>    <div id="test2" style="display:none">      <p>loading...</p>  </div>    <button onclick="run_test()">call long synchronous function!</button>

in fact, "loading" element never appears, , "some other data" replaced without our hypothetical user getting feedback during long wait.

what can ensure jquery hides , shows elements now, not once functions have finished executing?

the screen won't rendered until code stops execution. desired behavior, prevents rendering of dom in inconsistent state.

supposing really need run long synchronous task, , can fix or defer webworker, solution use settimeout:

function run_test() {      $('#test1').hide();      $('#test2').show();            settimeout(function(){         long_synchronous_function_call()               $('#test2').hide();         $('#test1').show();      },0);  }    function long_synchronous_function_call() {      $('#test1').html('<p>some other data</p>');      var date = new date();  	while ((new date()) - date <= 5000) {}  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>  <div id="test1">      <p>some data</p>  </div>    <div id="test2" style="display:none">      <p>loading...</p>  </div>    <button onclick="run_test()">call long synchronous function!</button>

just sure i'm not helping hiding bug: never synchronous ajax calls.

it is reasonable suggest when have legitimate , long synchronous operation happening in browser, though (for example computation or building of complex gui).


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -