Forcing repaint of element in resource-expensive operation

i have some issue:

I have a resource-expensive operation (generating elements into DOM). Previously, i just called the operation at start, but when there are many elements to generate, the page just stucks a few seconds, with unclickable elements, etc.

So i put a over full screen which shows the progress of generation of elements. But somehow the browser (Chromium on Ubuntu 14.04) does not render the progress.

Similar code (because mine is too long to paste):

function generate() {
    var $content = $('#content'), $progress = $('#progress'), count = 0;
    for(var x = 1; x < 100; x++) {
        for(var y = 1; y < 100; y++) {
            $content.append('<span>' + x + '-' + y + '</span>'); // adding an element into DOM
            $progress.html('Generated elements: ' + count++ );
    }
}

Elements are generated correctly, but the number of generated elements is not changing (stays at 0, which is default in HTML code).

Is there a way how to force browser to repaint the $progress element?

Upvotes: 3

Views: 63

Answers (1)

Jack
Jack

Reputation: 21163

This is untested but should get you pretty close to what you want.

   function generate() {
        var $content = $('#content'), $progress = $('#progress'), count = 0;
        for(var x = 1; x < 100; x++) {
            for(var y = 1; y < 100; y++) {
                (function(x, y) {
                        setTimeout(function() { 
                             $content.append('<span>' + x + '-' + y + '</span>');
                             $progress.html('Generated elements: ' + count++ );
                        }, Math.min(x + y, 100));
                })(x, y);
            }
        }
    }

Upvotes: 1

Related Questions