Do something before and after blocking code

javascript, jquery

Solution

The browser doesn't render changes to the DOM until all synchronous actions have completed, and your code returns control to the main event loop. This allows you to make lots of changes to the page without the user seeing all the intermediate forms -- it waits until you're done and just shows the final result.

One way to force immediate update is to use animations.

$(function () {
    jQuery("#modalDiv").show(5000);
    //This part takes up to a few seconds to execute and blocks the browser
    for (var i = 0; i < 10000; i++) {
        console.log("doing something");
    }
    jQuery("#modalDiv").hide(5000);
});

DEMO

Problem

Forgive my bad title, but right now, I don't even know what I don't know. If I have an HTML page that looks something like this: ``` <html> <head> <script> jQuery(document).ready(function(){ jQuery("#modalDiv").show(); //This part takes up to a few seconds to execute and blocks the browser for(var i = 0; i < 10000; i++){ console.log("doing something"); } jQuery("#modalDiv").hide(); }); </script> <style> #modalDiv{ background-color:red; height:100px; width:100px; } </style> </head> <body> <div id="modalDiv"></div> </body> </html> ``` The element with the ID "modalDiv" is never displayed on the page. I'm not trying to solve this "problem," I'm just trying to understand what is going on under the hood causing my script to behave as it does.

Original source