How to show a "working" indicator when inserting a large number of dom elements

When creating and inserting DOM elements, it seems that the functions used for the task are returned before the elements are displayed on the page.

Before embedding elements, I set the display property of the div to "block", and after inserting the elements I set the property to "none", the problem is that the indicator does not appear on the page. It can be done? Where $ is an alias for document.getElementById.

$('loading').className="visible";
var container = document.getElementById('container');
    for(var i=0; i< 50000; i++){
    var para = document.createElement('p');
    para.appendChild(document.createTextNode('Paragraph No. ' + i));
    container.appendChild(para);    
    }
$('loading').className="hidden";

It seems that createElement and / or appendChild are running asynchronously, so I hide the indicator almost immediately?

+3
source share
3 answers

, DOM script.

, setTimeout 0 . :

showLoadingIndicator();
setTimeout(addElements, 0);
function addElements() {
    // perform your loop here
    hideLoadingIndicator();
}
+3

setTimeout() - . "" :

$('loading').className="visible";
setTimeout(function() {
    var container = document.getElementById('container');
    for(var i=0; i< 50000; i++){
        var para = document.createElement('p');
        para.appendChild(document.createTextNode('Paragraph No. ' + i));
        container.appendChild(para);    
    }
    $('loading').className="hidden";
}, 0);
+7

You never want the browser to have too much time. It kills the user interface, including (unfortunately) animated gifs used as vague indicators of progress.

The solution is to split the process into, say, 50 calls using setTimeout () into a function that adds 1000 elements.

+3
source

Source: https://habr.com/ru/post/1702563/


All Articles