why loader image is not showing?

1.5k views Asked by At

I am having a function which take some time to complete it's process. So I am planning to display the process image until it's going to finish.

Please take a look at the sample here.when the user clicks on the button process will start. Here I put setTimeout function to make delay.But the processing image is not showing.

Sample Code

If I am placing the code for hiding the image inside setTimeout function it is working.

But in actual code that is also not working.

Also I tried with

$.when($("#loaderImg").show()).done(function(){
showSomeProcess()
$("#loaderImg").hide();
})

So please help me with this sample code. I dont understand why the processing image is not showing.

2

There are 2 answers

0
Ninja On BEST ANSWER

Use of promise will solve your problem. Updated fiddle also https://jsfiddle.net/3espztjw/5/

$("#startProcess").click(function(){
    $("#loaderImg").show();
    $.when(showSomeProcess()).then(function(){
        $("#loaderImg").hide();  
    })
});
var showSomeProcess=function(){
    var deferred = jQuery.Deferred()
    $("#progress").html("Process started");
    setTimeout(function(){
        $("#progress").html("Process end");
        deferred.resolve();
    },3000);
    return deferred.promise();
}
0
Jones Joseph On

Technically, the setTimeout() function does not execute in flow. It breaks the synchronous sequence. This does not mean it is asynchronous and running on separate thread. It just executes it outside the sequential order. So the hide() function executes before the task is actually completed and we don't see the loader.

It is asynchronous(partially) but definitely not running on concurrent thread.

So, something like this code wont actually work as expected:

$("#loaderImg").show();
    setTimeout(function(){
       $("#progress").html("Process end");
    },3000);
$("#loaderImg").hide(); 

The hide function will be triggered before 3 secs are completed.

This may help if you want to hide the loader after 3secs:

$("#loaderImg").show();
   setTimeout(function(){
      $("#progress").html("Process end");
      $("#loaderImg").hide(); 
   },3000);

Also, just because setTimeout() runs out of sync with the sequence doesn't mean it improves performance because its running on the same thread.

An example which does not work as expected:

$(function() {
  $('div').html("Started");
  setTimeout(function(){
    $('div').html("Working");
  },3000);
  $('div').html("Finished");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

Surely you can notice how the sequence goes in the above snippet.

Some working code:

$(function() {
  $('div').html("Started");
  $('div').html("Working");
  setTimeout(function() {
    $('div').html("Finished");
  }, 3000);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>