Show javascript execution progress

无人久伴 提交于 2019-11-27 20:45:34

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();

Perhaps you can put in a delay between showing the animated gif and running the heavy code.

Show the gif, and call:

window.setTimeout(myFunction, 100)

Do the heavy stuff in "myFunction".

You have to use a little more sophisticated technique to show the progress of the long running function.

Let's say you have a function like this that runs long enough:

function longLoop() {
    for (var i = 0; i < 100; i++) {
        // Here the actual "long" code
    }
}

To keep the interface responsive and to show progress (also to avoid "script is taking too long..." messages in some browsers) you have to split the execution into the several parts.

function longLoop() {
    // We get the loopStart variable from the _function_ instance. 
    // arguments.callee - a reference to function longLoop in this scope
    var loopStart = arguments.callee.start || 0;

    // Then we're not doing the whole loop, but only 10% of it
    // note that we're not starting from 0, but from the point where we finished last
    for (var i = loopStart; i < loopStart + 10; i++) {
        // Here the actual "long" code
    }

    // Next time we'll start from the next index
    var next = arguments.callee.start = loopStart + 10;
    if (next < 100) {

        updateProgress(next); // Draw progress bar, whatever.
        setTimeout(arguments.callee, 10);
    }
}

I haven't tested this actual code, but I have used this technique before.

Try setting a wait cursor before you run the function, and removing it afterwards. In jQuery you can do it this way:

var body = $('body');
body.css("cursor", "wait");
lengthyProcess();
body.css("cursor", "");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!