2

I'm getting response from this provider where there is a huge, deep array.

I only have to loop through this array and do some simple calculation but it's taking quite long to process.

What's the best practice to do this with JavaScript?

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54

2 Answers2

1

The best way to do heavy computation is to start a WebWorker. Remember that transferring large objects to a worker is slow, so you would probably like to get the response (like start an ajax) in the worker itself.

If you are stuck to one thread, you can use the following method to split the computation into smaller parts, but this will not help you if a single iteration takes too long.

function eachAsync(array, fn) {
  return new Promise(function(resolve, reject) {
    var index = 0;
    function chunk() {
      try {
        var end = performance.now() + 20;
        for(;;) {
          if (index < array.length) {
            var current = index++;
            fn(array[current], current);
          } else {
            resolve();
            break;
          }
          if (performance.now() >= end) {
            schedule();
            break;
          }
        }
      } catch(e) {
        reject(e);
      }
    }
    function schedule() {
      setTimeout(chunk, 10);
    }
    schedule();
  });
}
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
0

If you are using HTML5 with a modern browser you can use WebWorkers: http://ejohn.org/blog/web-workers/

Or you can use a homegrown method: Execute Background Task In Javascript

Community
  • 1
  • 1
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • 2
    Since it is tagged with `node.js` I believe there are more threading options for OP. – PSWai Dec 09 '15 at 03:01
  • @SteveWellens what is the most popular option for node.js? From what i found, `node-webworker-threads` performance doesn't seem very impressive in their example. – Tuan Anh Tran Dec 09 '15 at 03:50
  • @TuanAnhTran I don't know what the most popular option is. If they are a bit slow...who cares: they are in a background thread. – Steve Wellens Dec 09 '15 at 05:13
  • @SteveWellens if they are in background it does not mean they can run slowly. – Ravi Sharma Oct 22 '21 at 18:33