Show javascript execution progress

Midhat picture Midhat · Jun 8, 2010 · Viewed 8.1k times · Source

I have some javascript functions that take about 1 to 3 seconds. (some loops or mooML templating code.)

During this time, the browser is just frozen. I tried showing a "loading" animation (gif image) before starting the operation and hiding it afterwords. but it just doesnt work. The browser freezes before it could render the image and hides it immediately when the function ends.

Is there anything I can do to tell the browser to update the screen before going into javascript execution., Something like Application.DoEvents or background worker threads.

So any comments/suggestions about how to show javascript execution progress. My primary target browser is IE6, but should also work on all latest browsers

Answer

Sean Kinsey picture Sean Kinsey · Jun 8, 2010

This is due to everything in IE6 being executed in the same thread - even animating the gif.

The only way to ensure that the gif is displayed prior to starting is by detaching the execution.

function longRunningProcess(){
    ....

    hideGif();
}

displayGif();
window.setTimeout(longRunningProcess, 0);

But this will still render the browser frozen while longRunningProcess executes.
In order to allow interaction you will have to break your code in to smaller fragments, perhaps like this

var process = {
    steps: [
        function(){
            // step 1
            // display gif
        },
        function(){
            // step 2
        },
        function(){
            // step 3
        },
        function(){
            // step 4
            // hide gif
        }
    ],
    index: 0,
    nextStep: function(){
        this.steps[this.index++]();
        if (this.index != this.steps.length) {
            var me = this;
            window.setTimeout(function(){
                me.nextStep();
            }, 0);
        }
    }
};

process.nextStep();