Tim
Tim

Reputation: 424

Spinner button that starts spinning when function is called and stops when it ends

I'm trying to make a spinner button that will spin while I make an AJAX request and stop when the answer is received.

I've got the AJAX handled but the spinning doesn't seem to work with the following code:

function refresh (id){
    var iconElem = document.getElementById("spinner" + id);
    iconElem.classList.add('fa-spin');
    sleep(5000);
    var buttonRefresh = document.getElementById("refreshButton" + id); 
    buttonRefresh.classList.remove("fa-spin");

};

Note : I have replaced the ajax function with a sleep (implemented elsewhere, but it works like like it should) since I am in a non-php environment.

What happens here is that the the class "fa-spin" is being added while the sleep is over, even though it comes after in the code... Am I missing some kind of "refresh" that I need to execute in order to make the added class effective ?

Upvotes: 1

Views: 627

Answers (3)

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

Changes to the style or content of the document become effective only when the JavaScript function finishes and returns to the main event loop. Therefore, assuming your sleep() function works as expected (by doing a busy wait or something like that, although that is not actually sleeping), you can only see the total effect of all changes when the function returns. If you follow the advice of the other answers and remove the style in the callback of the AJAX call, you will be fine.

Upvotes: 1

Liad Yogev
Liad Yogev

Reputation: 874

Here is the simplest solution with a callback:

function sleep(callback,timeout){
  setTimeout(callback,timeout)
}

sleep(() => {
  //stop spinner here
},200)

Anyways, I suggest you to read more here

If you are doing an ajax request, you can also use the async:false header to make your request synced, and then your code should work.

Upvotes: 1

Srimoyee Sen
Srimoyee Sen

Reputation: 191

You need to stop the spinning in the completion callback of the ajax call as it is a async call. What you are doing here is starting and then immediately stopping the spinner before the ajax call even finishes.

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
   // stop the spinner here
  }
});

Upvotes: 1

Related Questions