How to give javascript "breath"

I have javascript / jquery code (for an internal website) that handles most of the client side on a large table. It works a little slowly, but that's fine.

The problem is that it freezes the browser while working with loops that it should execute. This has two undesirable effects:

  • The handler (animated gif, but I also tried spin.js and it has the same problem) freezes.
  • If there are enough rows in the table, the loops take a lot of time, and the browser reports a script immunity

Is there a way that I can have some kind of β€œbreathing” expression in the code so that every (say) 100 iterations it stops to let the spinner and browser know that the script is still working in the subject? Something like (pseudo-code):

for (i=0;i<20000;i++)
{
    fnProcessRow();
    if (i % 100 == 0) breath();
}
+5
source share
3 answers

One way to break your javascript is to split the processing into pieces and use setTimeout () to execute the next β€œpiece”

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

+1
source

There is no established method for this, as it depends on your code. Something like this will work:

fnProcessRows(0, 10000);

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

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

10000 . , "" "" , . , , .

, , 10000 - , ; , .

+1

See this question .

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

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

In some (most?) Browsers that make it re-plan and display.

0
source

All Articles