Ben Holness
Ben Holness

Reputation: 2707

How to let javascript "breath"

I have some javascript/jquery code (for an internal website) that does a lot of client side processing on a large table. It runs a little slowly, but that's OK.

The problem is that it freezes the browser while running through the loops that it needs to do. This has two effects that are undesirable:

  1. The processing spinner (an animated gif, but I also tried spin.js and that has the same issue) freezes.
  2. If there are enough rows in the table, the loops take a long time and the browser reports an unresponsive script

Is there a way I can have some sort of a "breath" statement in the code, such that every (say) 100 iterations, it pauses to let the spinner spin and the browser know that the script is still working on it? Something like (pseudo code) :

for (i=0;i<20000;i++)
{
    fnProcessRow();
    if (i % 100 == 0) breath();
}

Upvotes: 5

Views: 820

Answers (3)

Brandon
Brandon

Reputation: 39192

See this question.

If you do not want to go the setTimeout/setInterval route, try adding:

if (i % 100) { $("selector for your animated image").width(); }

On some (most?) browsers that will force it to re-layout and render.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

There is no set method for doing this as it depends very specifically on your code. Something like this would work:

fnProcessRows(0, 10000);

function fnProcessRows(start, end) {
    /* do row processing */

    if (end < totalRows) {
        setTimeout(function () {
            fnProcessRows(start + 10000, end + 10000);
        }, 1000);
    }
});

This will process 10000 rows with a one second break in between. This can have potentially weird side effects like displaying the "processed" rows with "unprocessed" rows, which may be undesirable. If it's not, then this should be a pretty simple solution to help out.

You can of course reduce 10000 to something else if it's still unresponsive; it should be unresponsive for only very short periods of time that the user would have a hard time noticing.

Upvotes: 1

Lee Taylor
Lee Taylor

Reputation: 7994

One way to break up your javascript is to divide your processing into chunks and use setTimeout() to perform the next "chunk"

Let me know if you need some code to show you what I mean.

Upvotes: 1

Related Questions