DOM refresh on long running function

后端 未结 12 2325
醉话见心
醉话见心 2020-11-27 20:54

I have a button which runs a long running function when it\'s clicked. Now, while the function is running, I want to change the button text, but I\'m having problems in some

12条回答
  •  死守一世寂寞
    2020-11-27 21:27

    As described in the "Script taking too long and heavy jobs" section of Events and timing in-depth (an interesting reading, by the way):

    [...] split the job into parts which get scheduled after each other. [...] Then there is a “free time” for the browser to respond between parts. It is can render and react on other events. Both the visitor and the browser are happy.

    I am sure that there are many times in which a task cannot be splitted into smaller tasks, or fragments. But I am sure that there will be many other times in which this is possible too! :-)

    Some refactoring is needed in the example provided. You could create a function to do a piece of the work you have to do. It could begin like this:

    function doHeavyWork(start) {
        var total = 1000000000;
        var fragment = 1000000;
        var end = start + fragment;
    
        // Do heavy work
        for (var i = start; i < end; i++) {
            //
        }
    

    Once the work is finished, function should determine if next work piece must be done, or if execution has finished:

        if (end == total) {
            // If we reached the end, stop and change status
            document.getElementById("btn").innerHTML = "done!";
        } else {
            // Otherwise, process next fragment
            setTimeout(function() {
                doHeavyWork(end);
            }, 0);
        }            
    }
    

    Your main dowork() function would be like this:

    function dowork() {
        // Set "working" status
        document.getElementById("btn").innerHTML = "working";
    
        // Start heavy process
        doHeavyWork(0);
    }
    

    Full working code at http://jsfiddle.net/WsmUh/19/ (seems to behave gently on Firefox).

提交回复
热议问题