I’ll explain a little about this first but I’ll try to keep it short and simple.
I have designed a map, which its information is added on load using ajax. Using a for loop, it adds six data attributes to every div where the ID matches. I’m hoping to add a loading progress function as it takes about 4 – 8 seconds to complete and this is what I’m having a problem with.
This is the full part of the code in question. You can skip if you want as I written the parts I’m having issues with underneath.
$.ajax({
// Get information
type:'GET',
url:'../../DataFile.php',
data:"#roomtable table",
success: function(data){
//Total Count of Rooms
totCount = $(".room").length;
//Initalise Count
count = 0;
//For each room
$('.room').each(function(){
thisRoom = $(this);
//Increase Count
count++;
//For each row in data table
$($(data).find('tr')).each(function() {
//If ID matched first cell
if (thisRoom.attr('id') == $(this).find('td:nth(0)').html())
{
.....
//Add data attributes from the other cells.
.....
}
});
//Write the current count as a percentage.
$('#count').text(Math.round(count/totCount*100));
});
}
});
The part I’m having trouble with is on every pass through the each function I was hoping the count would increase by the percentage. e.g 1/100…. 16/100… 25/100… and so. But what is happening is it just pauses until the data attributes have been written and jumps straight to 100%.
count = 0;
$('.room').each(function(){
count++;
$('#count').text(Math.round(count/totCount*100));
});
How come the above code doesn’t write the new count on each pass? Please can someone help me where I am going wrong. I apologise the question is a little bit wordy and thanks in advance.
JavaScript is single-threaded, when your code is busy doing some computation, UI thread has not chance to update. You may consider use
setTimeoutor something like Underscore’s defer function to achieve your goal. The documentation ofdeferis as follows:Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating.