Reputation: 3317
I have a function that's running for 2-3 seconds on the client (no ajax calls). I'm trying to show a "Busy/Processing" animation while this operation is running.
simplified code is as followed:
var ajaxContainer = $('.spinner');
// show
$(ajaxContainer ).show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
ProcessItem(value.itemID);
});
// hide
$(ajaxContainer ).hide();
but this does not work as expected. the result that i get is that the operation runs without showing the spinner. although it does show when the operation ends.
I saw some posts online mentioning that this could be done by using windows.setTimeout(). but since this operation is based on a dynamic number of items i would not want to set a specific timeout number in advance. instead i'd like to show the spinner when the operation starts, and hide it when it's finished.
is there an elegant way to achieve this?
Upvotes: 2
Views: 1315
Reputation: 4578
I think you have to add a callback parameter to ProcessItem
function in order to check if all items have been processed. Try this way:
function ProcessItem(id, callback){
//do process and after call callback function
callback();
}
var processedItemsQuantity = 0;
var ajaxContainer = $('.spinner');
ajaxContainer.show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
ProcessItem(value.itemID, function(){
if (items.length - 1 == processedItemsQuantity){
ajaxContainer.hide();
}
else processedItemsQuantity++;
});
});
Upvotes: 2
Reputation: 7067
You can't show a spinner in a synchronous operation because it's blocking the UI (ajax is asynchronous, that's why it works).
What you need is to put your code in a Web Worker.
Upvotes: 0