Question

I have been adding loaders in my sites usually before a call to the database and therefor usually before using a $.post function.

I have never had any problem until now that I face myself trying to add a loader before some random code which takes a while to be executed.

I can see how the append element is loaded into the DOM but it is not being rendered.

This is the example code which illustrates the problem:

$('.demo').click(function(){

    alert("Starting...");

    //won't be rendered until the FOR finishes
    $(this).append(' Loading...');

    for(var i = 0; i<800000000; i++){
     var nothing = 1 + Math.floor(Math.random() * i);
    }

});

Here's the living example: http://jsfiddle.net/88398/1/

How could I make the loader to be rendered before the execution of the following code?

Thanks.

Was it helpful?

Solution

This is because after updating the dom, the browser is not getting any time to repaint the UI till the function completes.

One possible solution to use setTimeout() to delay the task which will provide the time for browser to update the UI and then execute the setTimeout callback.

$('.demo').click(function(){
    alert("Starting...");
    $(this).append(' Loading...');

    setTimeout(function(){
        for(var i = 0; i<800000000; i++){
            var nothing = 1 + Math.floor(Math.random() * i);
        }
    }, 10)
});

Demo: Fiddle

The reason is a browser tab runs like a single thread that is at one time the browser can do only a single task. Meaning it can either update the UI or run the script.

In your case you have a function, any changes done with in it(dom update) will take effect only after the completion of the function execution

I hope I got the terminologies correct

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top