JavaScript execution temporarily overhangs

I have a web application that uses jQuery / JavaScript heavily . It contains a large array in memory, and the user filters it by entering a text field.

Problem. When the filtering algorithm works, the application becomes unresponsive , and the browser may even ask the user to continue the script.

Optimally, I would like the filter function to execute in a separate thread to avoid unpredictability. Is this possible anyway? Alternatively, I would like to show a rotating hourglass or the like, but browsers cannot display animated GIFs when dealing with heavy scenarios.

What is the best way to attack a problem?

+5
source share
3 answers

Browsers execute scripts in the main event processing thread. This means that any long scripts may delay the browser queue.

You have to split the filter logic into pieces and run them on the timeout callback. You can use the space in 0 mills between executions. 0 milli is just a suggestion to the browser, but the browser will use the gap between subsequent callbacks to clear its turn of events. Timeout - As a rule, long scripts should be executed in a browser environment to prevent page "freezing".

+3
source

- "-" , , .

+2

, , , , , for. for, setTimeout(), , . :

// Generic function to execute a callback a given number
// of times with a given delay between each execution
function timeoutLoop(fn, startIndex, endIndex, delay) {
    function doIteration() {
        if (startIndex < endIndex){
            fn(startIndex++);
            setTimeout(doIteration, delay);
        }
    }
    doIteration();
}

// pass your function as callback
timeoutLoop(function(i) {
   // current iteration processing here, use i if needed;
}, 0, 100, 0);

: http://jsfiddle.net/nnnnnn/LeZxM/1/

, , , , , , , chunkSize timeoutLoop(), , ( fn()) ..

+2

All Articles