Himaan Singh Himaan Singh - 4 months ago 17
jQuery Question

Loader not shown when javascript is running but is shown when debugging

My CSS:

.loader1 {
background-color: rgba(255, 255, 255, .8);
position: fixed;
left: 0px;
top: 0px;
z-index: 1000;
height: 100%;
width: 100%;
overflow: hidden;
background-image: url(../Content/images/ezgif-1527767856.gif);
background-position: center;
background-repeat: no-repeat;
display: block;
}


My javascript:

function filterme() {
$("#loader1").show();

// in between I have a lot of code that takes time to run.
$("#loader1").hide();
}


My HTML:

<div class="loader1" id="loader1" style="display:none"></div>
<button type="button" onclick="filterme()">Click ME</button>


Clicking the button runs the javascript fine but the loader is not shown.

When I use a debugger and check it the loader is shown. How do I make it visible in non debugging mode?

Answer

It sounds like this is a threading problem. The browser is so busy running your CPU-intensive, long-running code that it doesn't quite get around to updating what's visible on the page before it's time to hide it again anyway.

So, perhaps this:

function filterme() {
    $("#loader1").show();
    setTimeout(function() {
        //in between i have a huge code that takes time to run
        $("#loader1").hide();
    }, 10);
}

That is, introduce a tiny delay between showing #loader1 and then executing the code. This gives the browser a moment to handle the UI update before diving in headfirst to the intensive stuff.

As an aisde, don't use onclick= to create event handlers. In your JavaScript, do:

$(document).ready(function() {
    $('button').click( filterme );
});