Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show a 'working' indicator while inserting a big numbers of dom elements

Tags:

javascript

dom

While creating and inserting DOM element's, it seems that the functions used for the task are returning before the elements show in the page.

Before starting to insert the elements I set the display property of a div to 'block' and after inserting the elements I set the property to 'none', the problem is, the indicator is not showing in the page. It's possible to accomplish this? 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 appears as createElement and/or appendChild run asynchronously, so I'm hiding the indicator almost immediately?

like image 214
Cesar Avatar asked Nov 14 '25 11:11

Cesar


1 Answers

setTimeout() is the answer. A simple 'one-line' change for you:

$('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);
like image 69
Scott Evernden Avatar answered Nov 17 '25 05:11

Scott Evernden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!