Himaan Singh
Himaan Singh

Reputation: 707

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?

Upvotes: 1

Views: 1925

Answers (3)

Djordje Nedovic
Djordje Nedovic

Reputation: 765

It is quite late, but if anyone has the same issue, you can use Ajax with async: false and have the loader shown:

$.ajax({
    async: false,
    type: "POST",
    beforeSend: function () {
        $(".loader").css("display", "table");
    },
    success: function (data) {
    },
});

Just set the call function of the loader in the beforeSend event.

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37813

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 );
});

Upvotes: 3

Rashid Javed
Rashid Javed

Reputation: 62

Put your function outside document.ready function.

Upvotes: -1

Related Questions