David
David

Reputation:

Show a javascript loader image while function is executing

I want to click a button, show a loader image, execute a time-consuming function, hide the loader image. When I attempt this, the page freezes until the entire event runs, so the loader image is never seen.

Here is a sample:

$('#btn').click(function() {
    $('#LoadingImage').show();
    <time consuming function>
    $('#LoadingImage').hide();
});

How can I distinctly show the loader image, update the screen, run the function, hide the loader image?

Upvotes: 11

Views: 11526

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488624

Although what you have should work, try doing this:

$('#btn').click(function() {
    $('#LoadingImage').show();
    setTimeout(function() {
        <time consuming function>
        $('#LoadingImage').hide();
    }, 0);
});

This will escape the call stack of the event.

If THAT doesn't work, then post more details as to what this mystery time consuming function is.

Upvotes: 16

olliej
olliej

Reputation: 36803

For various reasons JS has to execute on the main thread, which means that painting is blocked as long as JS is executing -- even multiprocess architectures like chrome cannot repaint a tab if that tab is executing JS.

Your only way to get painting to occur will be to split up execution of your function, or move the function onto an html5 worker thread -- and they only work on the betas of Firefox and Safari (or more generally any sufficiently recent build of webkit proper)

Upvotes: 1

Related Questions