Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 641
Ben Holness Avatar asked Nov 03 '22 03:11

Ben Holness


2 Answers

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.

like image 121
Lee Taylor Avatar answered Nov 14 '22 10:11

Lee Taylor


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.

like image 42
Explosion Pills Avatar answered Nov 14 '22 10:11

Explosion Pills