tags:

views:

274

answers:

3

While creating and inserting dom element's, it seems that the fuctions 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???

+3  A: 

I believe that the DOM won't refresh until after the script has finished running.

To make it run asynchronously, you could try wrapping it in a setTimeout call, with a timeout of zero milliseconds. In pseudocode:

showLoadingIndicator();
setTimeout(addElements, 0);
function addElements() {
    // perform your loop here
    hideLoadingIndicator();
}
nickf
I never noticed how much pseudocode looks a lot like javascript.
Crescent Fresh
+6  A: 

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);
Scott Evernden
+2  A: 

You never want anything to take too long in the browser. It kills the UI, including (unfortunately) animated gifs used as indefinite progress indicators.

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

Nosredna
that's a good point, but a loading indicator doesn't necessarily have to be animated. it could be a simple text message reading "Please wait..."
nickf
Yes, but depending on the length of the wait, people will think the browser has crashed. And eventually, you'll get the unresponsive script alert from the browser.
Nosredna