Search code examples
javascripthtmldocumentappendchild

Client side javascript, creation of several elements and show each asap


Client side javascript code creates some elements (about 50-100) in a cycle:

for (var i = 0; i < list.length; i++) {
   var obj = document.createElement("DIV");
   obj.innerHTML = "<span class=\"itemId\">" + list[i].Id 
                   + "</span><!-- some more simple code --> ";

   mainObj.appendChild(obj);
}

There are some problems with browser rendering. For example, IE just freezes until it finishes the cycle, and then shows all elements at once. Is there a way to show each created element separately and immediately after appendChild()?


Solution

  • insert a delay between adding successive entries, with setTimeout().

    function insertEntry(list, ix) {
        if (ix == null) {
            ix = 0;
        }
        else if (ix < list.length) {
            var elt= document.createElement("DIV");
            var attr = document.createAttribute('id');
            attr.value = 'item'+ix;
            elt.setAttributeNode(attr);
            elt.innerHTML = "<span class='itemCls'>" + list[ix].Id + ':&nbsp;' + list[ix].Name +
                "</span><!-- some more simple code -->\n";
            mainObj.appendChild(elt);
            ix++;
        }
        if (ix < list.length) {
            setTimeout(function(){insertEntry(list, ix);}, 20);
        }
    }
    

    Kick it off with:

        insertEntry(myList);
    

    where myList is like this:

    var myList = [
        { Id : '1938377', Name : 'Sven'},
        { Id : '1398737', Name : 'Walt'},
        { Id : '9137387', Name : 'Edie'}
        ...
     };
    

    demo: http://jsbin.com/ehogo/4