Question

The documentation on JavaScript Web Workers is daunting. Basically, I have a heavy loop that causes the browser to hang a little bit. If I could offload that heavy loop onto another CPU core, then I could hopefully take some weight off the application and get it to run more smoothly. I am trying to modify a global variable using a simple loop:

var globalarr;

function webWorkerOp(CSV) {
    var lines = CSV.split("%");
    var items, obj, arr = [];

    for (var x = 0, len = lines.length; x < len; x++) {
        items = lines[x].split(",");
        obj = {};
        obj.a = +items[0];
        obj.b = +items[1];
        arr[x] = obj;
    }

    globalarr = arr;
}

How would I wrap this loop operation up into a web worker without causing a conflict with the primary program running code? The modification of the global variable will sure be a problem, I would think. Is it even possible to assign the new array to the globalarr var? Help is appreciated. Thanks!

Était-ce utile?

La solution

There is no way to modify a window.global from a web-worker, as the web-worker has no reference to the window object. You can communicate with the web-worker via window.postMessage. Using this approach, you can pass the array back to the main thread, and set the global there:

Main Thread

  var worker = new Worker('worker.js');
  var globalArr;

  worker.addEventListener('message', function (e) {
      globalArr = e.data;
  });

Worker Script

// do work
var arr = [1,3,5,]
self.postMessage(arr);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top