azamsharp
azamsharp

Reputation: 20096

JavaScript Script Taking Too Long to Execute. Getting the Script Taking Too Long Prompt

I have a JavaScript function buildTable which builds a very long HTML table.

 function buildTable() {

                for (var i = 0; i < rowCount; i++) {

     .. code to create table

}

}

The buildToolsetTable takes too much time and after few seconds IE 7 shows the prompt that if I want to keep running the script. I read that I can use window.setTimeout to make another call and refresh the execution but if someone has implementation then it will be super helpful.

Upvotes: 0

Views: 3524

Answers (1)

Alnitak
Alnitak

Reputation: 339985

You need something like this which breaks the loop up into a separate function that's called for each iteration:

(function(n) {
    var i = 0;

    function doWork() {
        // do one row's worth of stuff here
        ...

        if (++i < n) {
            setTimeout(doWork, 0);
        } else {
            // do your tidy up here
            ...
        }
    }

    doWork(); // start the first iteration
})(rowCount);

Calling setTimeout() will allow the browser to intersperse UI event handling with your own code.

See http://jsfiddle.net/alnitak/8wXTT/

For added fun, make the single iteration and tidy up functions callbacks, so you can make this code standalone and just pass in the required parameters.

Upvotes: 2

Related Questions