0

Is there a way to show a loading spinner while my javascript is running?

I want toshow something to the user while the page is waiting.....

This is taking about 5-6 secs..so I want to show a spinner or box while its waiting

$.each(ARRAY, function(key, item){
                            //IM DOING SOME LOGIC HERE
                        });
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151
  • 1
    See if this question helps: http://stackoverflow.com/questions/68485/how-to-show-loading-spinner-in-jquery – raddevon Aug 30 '13 at 18:28
  • 1
    Totally depends on what you are waiting for.. It looks like you are running some scripts.. which will freeze your browser until the completion of the script. – Selvakumar Arumugam Aug 30 '13 at 18:31

4 Answers4

1

Add a hidden loading image in your page, display it when you start you function and hide it again when the function completes.

<img src="loading image " id="loading">


function(){
  $("#loading").show();
  your logic
  $("#loading").hide();
}
Farhan
  • 752
  • 4
  • 10
0

This is just the first thing that came to mind. Probably not the best solution. But it does the job.. You could define a loading div and hide it by default. Then, while the each is doing its thing, show the loading div. So something like:

CSS:

   .hidden{display:none;}

HTML:

      <div class="loading hidden"></div>

JavaScript:

           function(){
               $('.loading').removeClass('hidden'); 
               $.each(ARRAY, function(key, item){

                    });
            }
jansmolders86
  • 5,449
  • 8
  • 37
  • 51
0

Try this. Works for me with a bootstrap 5.2 spinner, with the following referenced in the html:

  • bootstrap 5.2 stylesheet
  • referencing the bootstrap bundle script
  • jquery script

$function doLogic() {
    $("#loadingImg").css('visibility','visible');

    setTimeout(function() { // allow spinner to load before work starts
    
            // logic here to load page
            
    $("#loadingImg").hide();
    },5000); //5000ms = 5secs
    }
#loadingImg {
    width: 3rem;
    height: 3rem;
    align-self: center;
    visibility: hidden;
}
<div id="spinnerContainer">
  <div id="loadingImg" class="spinner-border" role="status">
    <span class="visually-hidden">Loading...</span>
  </div>
</div>
e-driver1
  • 45
  • 7
-1

This may be helpful for AJAX logic:

<img id="loadingImg" src="loding.gif"/>

$('#loadingImg')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/ajaxStop functions will fire whenever you do any AJAX calls and displays the loading spinner.

Alternatively, this may be helpful too:

function doLogic() {
    $('#loadingImg').show();

    setTimeout(function() { // allow spinner to load before work starts
        // logic here
    },500);

    $('#loadingImg').hide();
}
TheCarver
  • 19,391
  • 25
  • 99
  • 149