xwrs
xwrs

Reputation: 1297

Long-running loops in JavaScript and UI responsiveness

I had a code that processes a huge JSON array in a "for" loop.

for(var i = 0; item = arr[i]; i++) {
   //PROCESS item
}

The issue was with a Firefox browser. It shows a warning dialog that script is running too long. The following code was the solution

//not precise code example, but it's kind of.
delay(arr, 0);

function delay(arr, num) {
   //process array by parts with 50 elements in each part
   for(var i = 1; i <= 50; i++) { 
      //PROCESS arr[num];
      num += i;
   }
   if(num < arr.length) {
      setTimeout(function() { delay(arr, num); }, 100);
   }
}

I wondering if there is a more fabulous way to workaround complete UI freeze and make Firefox to don't show script debug dialog. Please advise. Thanks

Upvotes: 0

Views: 447

Answers (2)

Sven Sch&#252;rmann
Sven Sch&#252;rmann

Reputation: 612

I think web workers are what you need.

Here you can find an good introduction to web workers: link

Upvotes: 1

Flynn
Flynn

Reputation: 6191

If you are using Firefox, you might be looking for web workers, which allows you to spawn background threads.

Upvotes: 2

Related Questions