Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
918 views
in Technique[技术] by (71.8m points)

javascript - DOM style change waiting for pause

When this function is called, the style change on the "gif" element does not show up until "lotsOfProcessing()" finishes. However, when I uncomment the alert("test"), the style change is shown before the alert pops up.

What I am trying to do is have an animated gif displayed while lotsOfProcessing is running. This seemed pretty straight forward solution but it is clearly not working. Any suggestions / solutions?

function nameOfFuntion()
    {
        document.getElementById("gif").style.display = "inline";
        //alert("test");
        lotsOfProcessing();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JavaScript code executes on the same thread as the browser's rendering. Everything that needs to be drawn waits for JavaScript execution to complete - including the next frame of any GIF animation.

The only solution is to break your long processing code down into smaller parts and delay each part using timers.

For example:

function nameOfFuntion() {
    document.getElementById("gif").style.display = "inline";
    //alert("test");
    lotsOfProcessing();
}

function lotsOfProcessing() {
    var i = 0;
    window.setTimeout(function () {
        partOfIntenseProcessing();
        if (i < 1000000)
            i++, window.setTimeout(arguments.callee, 10);
    }, 10);
}

This will delay how long it will take for your processing to complete, but between timer execution the GIF can continue to animate.

You can also take a look at Web Workers, which allow you to run JavaScript operations in a background thread. However, they are not widely implemented yet (read: not available in Internet Explorer).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...