简体   繁体   中英

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

I'm using jQuery's .hide() and .show() functions to show a loading message while a potentially long synchronous webservice call executes.

When clicking the button in the below snippet, I would expect the text "Some data" to be immediately replaced with "Loading..." and then go back to "Some other data" after 5 seconds.

As you can see, that is not what 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 a long synchronous function!</button> 

In fact, the "Loading" element never appears, and "Some other data" is simply replaced without our hypothetical user getting any feedback during the long wait.

What can I do to ensure that jQuery hides and shows my elements now , not once all my functions have finished executing?

The screen won't be rendered until your code stops execution. This is almost always the desired behavior, as it prevents the rendering of the DOM in an inconsistent state.

Supposing you really need to run a long synchronous task, and you can fix that or defer it to a webworker , then a solution is to 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 a long synchronous function!</button> 

Just to be sure I'm not helping you hiding a bug: NEVER do synchronous ajax calls .

It is reasonable to do what I suggest when you really have a legitimate and somewhat long synchronous operation happening in your browser, though (for example a computation or the building of a complex GUI).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM