Reputation: 33678
I am populating a table with about 500 rows, which takes the browser a few seconds to render, while it appears frozen. This is why I want to display a message asking for the user's patience:
$.ajax({
url: '{{ search_url }}',
success: function (response) {
$('#progress').text('Rendering results, please wait...');
clear_table();
populate_table(response);
}
});
The message isn't displayed - apparently the browser (tested in Chrome 23) buffers all the DOM changes and renders them all in a single go.
As a workaround I found that when I delay populating the table until execution is back to the event loop the message is actually displayed:
$.ajax({
url: '{{ search_url }}',
success: function (response) {
$('#progress').text('Rendering results, please wait...');
window.setTimeout(function () {
clear_table();
populate_table(response);
}, 0);
}
});
I wonder if this method will always work or if there is a better technique for this case.
Upvotes: 9
Views: 3916
Reputation: 4264
This is happening because Javascript execution is single threaded. So until all your JS code is executed the browser will not do anything - in other words it will freeze. To prevent that I suggest you use the jQuery Async plugin (which is just a few lines of code) which will periodically give control back to the browser (by using setTimeout
). This prevents the browser from freezing and will display the wait message without any problems.
Upvotes: 3